如果我有一个清单:
["A","Bb","C","D","E","F","G"]
我怎样才能迭代它,以便我可以输出以下内容:
"A Bb C"
"D E F"
"G"
是我一直在闲逛的食谱。
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
你可以itertools.izip_longest
在这里使用:
>>> from itertools import izip_longest
>>> L = ["A","Bb","C","D","E","F","G"]
>>> for item in izip_longest(*[iter(L)]*3, fillvalue=''):
... print ' '.join(item)
...
A Bb C
D E F
G
获取[0:3]
, [3:6]
, [6:9]
, ...的子列表
>>> xs = ["A","Bb","C","D","E","F","G"]
>>> [' '.join(xs[i:i+3]) for i in range(0, len(xs), 3)]
['A Bb C', 'D E F', 'G']