Python相当于Ruby的each_slice(count)

the*_*ick 7 ruby python

蟒蛇相当于Ruby的each_slice(count)什么?
我想从列表中获取每个迭代的2个元素.
喜欢[1,2,3,4,5,6]我想1,2在第一次迭代中处理3,4然后5,6.
当然,使用索引值有一种迂回的方式.但有直接的功能或直接这样做吗?

Mar*_*ers 9

itertools文档中有一个名为grouper配方:

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)

使用这样:

>>> l = [1,2,3,4,5,6]
>>> for a,b in grouper(2, l):
>>>     print a, b

1 2
3 4
5 6
Run Code Online (Sandbox Code Playgroud)


nur*_*tin 5

我知道该语言的多位专家已经回答了这个问题,但我有一种不同的方法,使用生成器函数,该函数更容易阅读、推理并根据您的需要进行修改:

def each_slice(list: List[str], size: int):
    batch = 0
    while batch * size < len(list):
        yield list[batch * size:(batch + 1) * size]
        batch += 1   

slices = each_slice(["a", "b", "c", "d", "e", "f", "g"], 2)
print([s for s in slices])

$ [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]
Run Code Online (Sandbox Code Playgroud)

如果您需要每个切片具有批量大小,也许填充 None 或一些默认字符,您可以简单地将填充代码添加到产量中。如果您想要each_cons,则可以通过修改代码以逐一移动而不是逐批移动来实现。