按值分组列表 [英] Group list by values
本文介绍了按值分组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的列表:
Let's say I have a list like this:
list = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
我如何最优雅地将其分组以在Python中获得此列表输出:
How can I most elegantly group this to get this list output in Python:
list = [["A", "C"], ["B"], ["D", "E"]]
所以这些值按次值分组,但顺序保留下来...
So the values are grouped by the secound value but the order is preserved...
推荐答案
values = set(map(lambda x:x[1], list))
newlist = [[y[0] for y in list if y[1]==x] for x in values]
这篇关于按值分组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文