从列表中的每个键中获取具有最大值的元组
问题描述
我有一个这样的元组列表:
I have a list of tuples like this:
[(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]
我想保留每个元组的最大第一个值的元组具有相同的第二个值.例如 (2, 1)
和 (3, 1)
共享相同的第二个(键)值,所以我只想保留第一个值最大的那个 -> <代码>(3, 1)代码>.最后我会得到这个:
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...
解决方案
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
创建一个迭代器,它产生像 (0, <itertools._grouper object at 0x01321330>)
这样的对象,其中第一个值是键值,第二个一个是另一个迭代器,它使用该键给出所有元组.
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)
只选择最大值的元组,由于组的所有第二个值都相同(也是键),所以它给出最大值的元组第一个值.
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.
相关文章