Python 生成器,将另一个可迭代对象分组为 N 组

标签 python generator std

我正在寻找一个函数,它采用可迭代的 i 和大小 n 并产生长度为 n 的元组,它们是顺序值来自 i:

x = [1,2,3,4,5,6,7,8,9,0]
[z for z in TheFunc(x,3)]

给予

[(1,2,3),(4,5,6),(7,8,9),(0)]

标准库中是否存在这样的函数?

如果它作为标准库的一部分存在,我似乎找不到它,而且我已经用完了要搜索的术语。我可以自己写,但我宁愿不写。

最佳答案

如果您想将迭代器分组为 n 不填充的 block ,最后一个组具有填充值,请使用 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 block 时,您可以使用 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__ 已定义)。

关于Python 生成器,将另一个可迭代对象分组为 N 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3992735/

相关文章:

c++ - 声明一个 std::map 迭代器会导致一个奇怪的错误

c++ - 在 cout 中打印 getline() 字符串时出现奇怪的错误

python - Cython 中的 64 位整数

python - 将带有回调的函数转换为 Python 生成器?

c++ - 随机分布应该通过引用传递还是 C++ 中的对象成员

c++ - 此卸载区域中使用的 map<shared_ptr<TiXmlDocument>, double> 不可按位复制

python - 尝试运行 Flask 应用程序给出 "Address already in use"

python - Distutils 安装程序在 Mac OS X 上生成 .so 而不是 .dylib

python - Plotly strip 图 : avoid spacing between colors in px. strip

python3 fork 生成器