猿问

在第一个元素相同的所有值中找到第二个元素最大的元组

如何清理给定的元组列表,以便仅列出具有最大值的元组。

mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]

结果

[('a',6), ('b', 10), ('c', 8), ('d', 12)]


慕容3067478
浏览 229回答 3
3回答

慕姐8265434

把它变成字典:mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]d = {}for key, value in mytup:&nbsp; &nbsp; if d.get(key) < value:&nbsp; # d.get(key) returns None if the key doesn't exist&nbsp; &nbsp; &nbsp; &nbsp; d[key] = value&nbsp; &nbsp; &nbsp; # None < float('-inf'), so it'll workresult = d.items()

人到中年有点甜

我认为这应该工作:dict = {}for key, val in mytup:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; if dict[key] < val:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dict[key] = val&nbsp; &nbsp; except IndexError:&nbsp; &nbsp; &nbsp; &nbsp; dict[key] = val

慕慕森

Itertools是您的朋友,一线解决方案:from itertools import groupbyprint [ max(g) for _, g in groupby(sorted(mytup), lambda x: x[0] )]结果:[('a', 6), ('b', 10), ('c', 8), ('d', 12)]
随时随地看视频慕课网APP

相关分类

Python
我要回答