简体   繁体   English

从列表中的每个键获取具有最大值的元组

[英]Get tuples with max value from each key from a list

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) . 例如(2, 1)(3, 1)共享相同的第二(键)值,所以我只想保持最大第一个值 - > (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... 如果不是单行,我根本不介意,但我想知道一个有效的方法来解决这个问题......

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. groupby创建一个迭代器,它产生类似于(0, <itertools._grouper object at 0x01321330>) ,其中第一个值是键值,第二个是另一个迭代器,它给出了具有该键的所有元组。

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. max(items)只选择具有最大值的元组,并且由于组的所有第二个值都相同(并且也是键),因此它为元组提供了最大的第一个值。

A list comprehension is used to form an output list of tuples based on the output of these functions. 列表推导用于根据这些函数的输出形成元组的输出列表。

Probably using a dict: 可能使用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() ]
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)))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM