如果您想将迭代器分组为 n 的块不填充最后一个组具有填充值,请使用 iter(lambda: list(IT.islice(iterable, n)), []):
import itertools as IT
def grouper(n, iterable):
"""
>>> list(grouper(3, 'ABCDEFG'))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
"""
iterable = iter(iterable)
return iter(lambda: list(IT.islice(iterable, n)), [])
seq = [1,2,3,4,5,6,7]
print(list(grouper(3, seq)))
产量
[[1, 2, 3], [4, 5, 6], [7]]
在this answer的后半部分有对其工作原理的解释。
如果您想将迭代器分组为 n 的块并用填充值填充最终组,请使用 grouper recipe zip_longest(*[iterator]*n):
例如,在 Python2 中:
>>> list(IT.izip_longest(*[iter(seq)]*3, fillvalue='x'))
[(1, 2, 3), (4, 5, 6), (7, 'x', 'x')]
在 Python3 中,以前的 izip_longest 现在重命名为 zip_longest:
>>> list(IT.zip_longest(*[iter(seq)]*3, fillvalue='x'))
[(1, 2, 3), (4, 5, 6), (7, 'x', 'x')]
当您想将 序列 分组为 n 的块时,您可以使用 chunks 配方:
def chunks(seq, n):
# https://stackoverflow.com/a/312464/190597 (Ned Batchelder)
""" Yield successive n-sized chunks from seq."""
for i in xrange(0, len(seq), n):
yield seq[i:i + n]
请注意,与一般的迭代器不同,sequences by definition 有一个长度(即定义了 __len__)。