开发者

idiomatic way to take groups of n items from a list in Python? [duplicate]

This question already has answers here: Iterate over a string 2 (or n) characters at a time in Python (13 answers) Iterate an iterator by chunks (of n) in Python? (12 answers) 开发者_如何学Go Closed 9 years ago.

Given a list

A = [1 2 3 4 5 6]

Is there any idiomatic (Pythonic) way to iterate over it as though it were

B = [(1, 2) (3, 4) (5, 6)]

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) ]:

I can't help but feel there should be some clever hack using itertools or slicing or something.

(Of course, two at a time is just an example; I'd like a solution that works for any n.)

Edit: 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.


From 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜