Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I group equivalent items together in a Python list?

Tags:

python

list

I have a list like

x = [2, 2, 1, 1, 1, 1, 1, 1]

I would like to put the repeated numbers together like

[[2,2],[1,1,1,1,1,1]] 
like image 448
graph Avatar asked Aug 11 '11 12:08

graph


People also ask

Are groups of similar items?

"grouping together things" with the 'similar properties' is called classification. Explanation: All living things and elements are grouped based on the way they share their properties or characteristics and those with similar characteristics are grouped into a single group through classification.

Can a list in Python contain other lists?

We can have a list of many types in Python, like strings, numbers, and more. Python also allows us to have a list within a list called a nested list or a two-dimensional list.


1 Answers

[list(g) for k, g in itertools.groupby(iterable)]

This is exactly what itertools.groupby is for.

If you want nonconsecutive numbers grouped, like in the comment by @Michal,

[list(g) for k, g in itertools.groupby(sorted(iterable))]
like image 173
agf Avatar answered Sep 24 '22 07:09

agf