Python生成器将另一个可迭代项分组为N个组 [英] Python generator that groups another iterable into groups of N
本文介绍了Python生成器将另一个可迭代项分组为N个组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一个函数,该函数采用可迭代的i
和大小n
,并产生长度为n
的元组,这些元组是i
的顺序值:
I'm looking for a function that takes an iterable i
and a size n
and yields tuples of length n
that are sequential values from 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)]
标准库中是否存在这样的功能?
Does such a function exist in the standard library?
如果它作为标准库的一部分存在,我似乎找不到它,而且我已经用完了所有的搜索条件.我可以自己写,但我不愿意.
If it exists as part of the standard library, I can't seem to find it and I've run out of terms to search for. I could write my own, but I'd rather not.
推荐答案
See the grouper
recipe in the docs for the itertools
package
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
(不过,这是有几个问题的副本.)
(However, this is a duplicate of quite a few questions.)
这篇关于Python生成器将另一个可迭代项分组为N个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文