How to group elements in python by n elements [duplicate]
Well, the brute force answer is:
subList = [theList[n:n+N] for n in range(0, len(theList), N)]
where N
is the group size (3 in your case):
>>> theList = list(range(10))>>> N = 3>>> subList = [theList[n:n+N] for n in range(0, len(theList), N)]>>> subList[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
If you want a fill value, you can do this right before the list comprehension:
tempList = theList + [fill] * NsubList = [tempList[n:n+N] for n in range(0, len(theList), N)]
Example:
>>> fill = 99>>> tempList = theList + [fill] * N>>> subList = [tempList[n:n+N] for n in range(0, len(theList), N)]>>> subList[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 99, 99]]
You can use the grouper function from the recipes in the itertools documentation:
def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)