从Python列表中获取n个项目组的惯用方法? [英] idiomatic way to take groups of n items from a list in Python?
问题描述
给出一个清单
A = [1 2 3 4 5 6]
是否有任何惯用(Pythonic)方法迭代它,就好像它是
Is there any idiomatic (Pythonic) way to iterate over it as though it were
B = [(1, 2) (3, 4) (5, 6)]
除了索引之外?这感觉就像C的延续:
other than indexing? That feels like a holdover from C:
for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]:
我不能帮助,但觉得应该有一些聪明的黑客使用itertools或切片等。
I can't help but feel there should be some clever hack using itertools or slicing or something.
(当然,一次两个只是一个例子;我想要一个解决方案适用于任何n。)
(Of course, two at a time is just an example; I'd like a solution that works for any n.)
编辑:相关在Python中一次迭代字符串2(或n)个字符但是即使是最干净的解决方案(使用zip接受)也没有在没有列表理解和* -notation的情况下很好地推广到更高的n。
related Iterate over a string 2 (or n) characters at a time in Python but even the cleanest solution (accepted, using zip) doesn't generalize well to higher n without a list comprehension and *-notation.
推荐答案
来自 http://docs.python.org/library/itertools.html :
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)
i = grouper(3,range(100))
i.next()
(0, 1, 2)
这篇关于从Python列表中获取n个项目组的惯用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!