如何清理给定的元组列表,以便仅列出具有最大值的元组。
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)]
把它变成字典:
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()
我认为这应该有效:
dict = {}
for key, val in mytup:
try:
if dict[key] < val:
dict[key] = val
except IndexError:
dict[key] = val
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)]