例如,我有这样的简单列表:
l = [1,2,3,4,5,6,7,8,9]
我想以3个元素为一组进行迭代:
1,2,3
4,5,6
7,8,9
最简单的方法是什么?
答案 0 :(得分:5)
棘手,但众所周知的方式(来自itertools
grouper recipe):
>>> zip(*[iter(l)] * 3))
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
可以写成
>>> it = iter(l)
>>> zip(it, it, it)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
答案 1 :(得分:2)
你可以这样做:
l = [1,2,3,4,5,6,7,8,9]
result = [l[i:i+3] for i in range(0,len(l),3)]
>>> print result
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> for i in result:
... print(i)
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
答案 2 :(得分:2)
您可以编写简单的生成器
def group_gen(lst, n):
for i in range(0,len(lst), n):
yield l[i:i+n]
for a,b,c in group_gen(l, 3):
print(a,b,c)
结果:
1 2 3
4 5 6
7 8 9