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

时间:2013-10-24 13:45:27

标签: 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的时间,但它很难看,因为我一直在列表和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

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用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]]

答案 1 :(得分:1)

使用itertools.groupby

>>> 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]]