[英]Find those tuples in which the second element is maximum among all values with same first element
How to sanitize a given list of tuples, such that only tuples with maximum values are listed. 如何清理给定的元组列表,以便仅列出具有最大值的元组。
mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]
Result 结果
[('a',6), ('b', 10), ('c', 8), ('d', 12)]
Turn it into a dictionary: 把它变成字典:
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()
I think this should work: 我认为这应该工作:
dict = {}
for key, val in mytup:
try:
if dict[key] < val:
dict[key] = val
except IndexError:
dict[key] = val
Itertools is your friend, one line solution: Itertools是您的朋友,一线解决方案:
from itertools import groupby
print [ max(g) for _, g in groupby(sorted(mytup), lambda x: x[0] )]
Results: 结果:
[('a', 6), ('b', 10), ('c', 8), ('d', 12)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.