Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group elements in python by n elements [duplicate]

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 
like image 949
TheOne Avatar asked Feb 14 '11 23:02

TheOne


People also ask

How do you group similar values in a list in Python?

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.

How do you create a group list in Python?

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.

How do you check if two elements are the same in a list Python?

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.


1 Answers

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]] 
like image 76
Mike DeSimone Avatar answered Oct 14 '22 07:10

Mike DeSimone