[英]Find those tuples in which the second element is maximum among all values with same first element
如何清理給定的元組列表,以便僅列出具有最大值的元組。
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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.