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]]
[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))]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.