Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I'd like to get groups of size n elements from a list l:
ie:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
The groupby method will return a list of the tuples with the element and its group. In every iteration, convert the group of similar elements into a list. Append the list to the empty list. Print the result.
List grouping in Python using set function. In this method, there is no need of importing any modules. We just extract all the values in a list and store the unique values using the set function.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.
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] * N subList = [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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With