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

南笙酒味 提交于 2019-11-26 21:37:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!