【发布时间】:2016-12-27 20:02:49
【问题描述】:
所以使用itertools.groupby() 拆分列表相当简单。
>>> import itertools as it
>>> iterable = it.groupby([1, 2, 3, 4, 5, 2, 3, 4, 2], lambda p: p==2)
>>> for x, y in iterable:
... print(x, list(y))
... next(iterable)
False [1]
False [3, 4, 5]
False [3, 4]
按预期工作。但是使用zip这种常见的python习语多次向上迭代迭代器以一次遍历2个似乎会破坏事情。
>>> iterable = it.groupby([1, 2, 3, 4, 5, 2, 3, 4, 2], lambda p: p==2)
>>> for (x, y), _ in zip(iterable, iterable):
... print(x, list(y))
False []
False []
False []
添加print(y) 显示了预期的嵌套可迭代<itertools._grouper object at 0xXXXXXXXX>,但我显然遗漏了为什么grouper 对象为空的原因。有人能解释一下吗?
如果我有一个不均匀的列表并使用itertools.zip_longest,我会得到一个更奇怪的结果:
>>> iterable = it.groupby([1, 2, 3, 4, 5, 2, 3, 4], lambda p: p==2)
>>> for (x, y), _ in it.zip_longest(iterable, iterable, fillvalue=None):
... print(x, list(y))
False []
False []
False [4]
更新:简单的解决方法是使用itertools.islice():
>>> iterable = it.groupby([1, 2, 3, 4, 5, 2, 3, 4, 2], lambda p: p==2)
>>> for x, y in it.islice(iterable, None, None, 2):
... print(x, list(y))
False [1]
False [3, 4, 5]
False [3, 4]
【问题讨论】:
标签: python python-3.x itertools