从列表中的每个键获取具有最大值的元组 [英] Get tuples with max value from each key from a list

查看:65
本文介绍了从列表中的每个键获取具有最大值的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的元组列表:

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.

这篇关于从列表中的每个键获取具有最大值的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆