如何清理给定的元组列表,以便仅列出具有最大值的元组。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)]
3 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
把它变成字典:
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:
if d.get(key) < value: # d.get(key) returns None if the key doesn't exist
d[key] = value # None < float('-inf'), so it'll work
result = d.items()
人到中年有点甜
TA贡献1895条经验 获得超7个赞
我认为这应该工作:
dict = {}
for key, val in mytup:
try:
if dict[key] < val:
dict[key] = val
except IndexError:
dict[key] = val
慕慕森
TA贡献1856条经验 获得超17个赞
Itertools是您的朋友,一线解决方案:
from itertools import groupby
print [ max(g) for _, g in groupby(sorted(mytup), lambda x: x[0] )]
结果:
[('a', 6), ('b', 10), ('c', 8), ('d', 12)]
添加回答
举报
0/150
提交
取消