问题
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]]
回答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))]
来源:https://stackoverflow.com/questions/7025581/how-can-i-group-equivalent-items-together-in-a-python-list