0

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

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)]
4

3 回答 3

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()
于 2013-06-13T16:23:50.500 回答
1

我认为这应该有效:

dict = {}
for key, val in mytup:
    try:
        if dict[key] < val:
            dict[key] = val
    except IndexError:
        dict[key] = val
于 2013-06-13T16:25:39.740 回答
0

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)]
于 2013-06-13T16:31:48.040 回答