Python元组列表

Python元组列表,python,list,tuples,Python,List,Tuples,您能帮我转换Python列表吗: [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')] 以便: (1,'a')是索引0 (2,'b'),(2,'c')都是索引1 (3,'d'),(3,'e')都是索引2 简单地说,元素[0]相等的所有元组都有相同的索引 谢谢你,为了营救!: lst = [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')] lst.sort(key=lambda x: x[0])

您能帮我转换Python列表吗:

[(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')]
以便:
(1,'a')
是索引0

(2,'b'),(2,'c')
都是索引1

(3,'d'),(3,'e')
都是索引2

简单地说,元素[0]相等的所有元组都有相同的索引

谢谢你,

为了营救!:

lst = [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')]
lst.sort(key=lambda x: x[0])  #Only necessary if your list isn't sorted already.
new_lst = [list(v) for k,v in itertools.groupby(lst,key=lambda x:x[0])]
如果需要,可以使用
操作符.itemgetter(0)
而不是
lambda

演示:


不清楚您想要什么,但这将根据项目的第一个元素将项目分组到列表中

groups = collections.defaultdict(list)
for x,y in items:
    groups[x].append(y)

@乔恩不敢相信我漏掉了那个打字错误。对不起,没有仔细校对。
groups = collections.defaultdict(list)
for x,y in items:
    groups[x].append(y)