If I have a list with:
["A","Bb","C","D","E","F","G"]
how can I iterate over it so that I can output the following:
"A Bb C"
"D E F"
"G"
If I have a list with:
["A","Bb","C","D","E","F","G"]
how can I iterate over it so that I can output the following:
"A Bb C"
"D E F"
"G"
Get sublists of [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']
Is a recipe that I keep hanging around.
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
You can use itertools.izip_longest
here:
>>> 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