Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python——对满足谓词的连续元素进行分组_Python_Itertools - Fatal编程技术网

Python——对满足谓词的连续元素进行分组

Python——对满足谓词的连续元素进行分组,python,itertools,Python,Itertools,我想对满足谓词的连续元素进行分组。这样一个函数的doctest看起来像 >>> group([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x != 0) [[1, 2, 3], [4, 5], [6]] >>> group([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x == 0) [[0], [0, 0]] 我已经写了一个原型,我使用了itertool的takewhile,

我想对满足谓词的连续元素进行分组。这样一个函数的doctest看起来像

>>> group([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x != 0)
    [[1, 2, 3], [4, 5], [6]] 
>>> group([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x == 0)
    [[0], [0, 0]]
我已经写了一个原型,我使用了itertool的takewhile,但它很难看,因为我一直在列表和iter之间转换。我也不想坚持阅读列表的索引,因为它感觉效率低下。有人能告诉我如何以正确的方式混合和搭配itertools吗

from itertools import takewhile

def group(l, p):
    blocks = []
    while True:
        i = iter(l)
        taken = list(takewhile(p, i))
        l = list(i)
        if len(taken) > 0:
            blocks.append(taken)
        if len(l) == 0:
            return blocks
谢谢

您可以使用:

您可以使用:

使用:

使用:


itertools.groupby有什么问题?我不知道如何使用它,但现在我可以了。谢谢大家。
itertools.groupby有什么问题吗?我不知道如何使用它,但现在我可以了。谢谢大家。
In [22]: import itertools as IT

In [23]: [list(g) for k, g in IT.groupby(
          [1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x != 0) if k]
Out[23]: [[1, 2, 3], [4, 5], [6]]
>>> import itertools
>>>
>>> data = [1, 2, 3, 0, 4, 5, 0, 0, 6]
>>> xs = [list(grp) for k, grp in itertools.groupby([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x == 0)]
>>> xs
[[1, 2, 3], [0], [4, 5], [0, 0], [6]]

>>> xs[data[0] == 0::2]
[[1, 2, 3], [4, 5], [6]]
>>> xs[data[0] != 0::2]
[[0], [0, 0]]