如何在Python列表中将等效项分组在一起? [英] How can I group equivalent items together in a Python list?
本文介绍了如何在Python列表中将等效项分组在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似
x = [2, 2, 1, 1, 1, 1, 1, 1]
我想像
[[2,2],[1,1,1,1,1,1]]
推荐答案
[list(g) for k, g in itertools.groupby(iterable)]
这正是 itertools.groupby
的用途.
This is exactly what itertools.groupby
is for.
如果您希望将非连续数字分组,例如@Michal的评论中
If you want nonconsecutive numbers grouped, like in the comment by @Michal,
[list(g) for k, g in itertools.groupby(sorted(iterable))]
这篇关于如何在Python列表中将等效项分组在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文