Get tuples with max value from each key from a list

我怕爱的太早我们不能终老 提交于 2020-11-24 19:13:23

问题


I have a list of tuples like this:

[(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]

I want to keep the tuples which have the max first value of every tuple with the same second value. For example (2, 1) and (3, 1) share the same second (key) value, so I just want to keep the one with the max first value -> (3, 1). In the end I would get this:

[(1, 0), (3, 1), (6, 2), (2, 3)]

I don't mind at all if it is not a one-liner but I was wondering about an efficient way to go about this...


回答1:


from operator import itemgetter
from itertools import groupby

[max(items) for key, items in groupby(L,key = itemgetter(1))]

It's assuming that you initial list of tuples is sorted by key values.

groupby creates an iterator that yields objects like (0, <itertools._grouper object at 0x01321330>), where the first value is the key value, the second one is another iterator which gives all the tuples with that key.

max(items) just selects the tuple with the maximum value, and since all the second values of the group are the same (and is also the key), it gives the tuple with the maximum first value.

A list comprehension is used to form an output list of tuples based on the output of these functions.




回答2:


Probably using a dict:

rd = {}
for V,K in my_tuples:
  if V > rd.setdefault(K,V):
    rd[K] = V
result = [ (V,K) for K,V in rd.items() ]



回答3:


import itertools
import operator
l = [(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]
result = list(max(v, key=operator.itemgetter(0)) for k, v in itertools.groupby(l, operator.itemgetter(1)))



回答4:


You could use a dictionary keyed on the second element of the tuple:

l = [(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]
d = dict([(t[1], None) for t in l])
for v, k in l:
  if d[k] < v:
    d[k] = v 
l2 = [ (v, k) for (k, v) in d.items() if v != None ]
print l2


来源:https://stackoverflow.com/questions/7590932/get-tuples-with-max-value-from-each-key-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!