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]]
"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.
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.
[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))]
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