从列表中的每个键获取具有最大值的元组
我有一个像这样的元组列表:
[(1, 0), (2, 1), (3, 1), (6, 2), (3, 2), (2, 3)]< /code>
我想保留每个元组的最大第一个值具有相同第二个值的元组。例如 (2, 1)
和 (3, 1)
共享相同的第二个(键)值,所以我只想保留具有最大第一个值的那个 - > <代码>(3, 1)。最后我会得到这个:
[(1, 0), (3, 1), (6, 2), (2, 3)]
我根本不介意它是否是不是一句话,但我想知道一种有效的方法来解决这个问题......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您的初始元组列表是按键值排序的。
groupby
创建一个迭代器,生成类似(0,)
的对象,其中第一个值是键值,第二个值是另一个值迭代器给出带有该键的所有元组。max(items)
只是选择具有最大值的元组,并且由于该组的所有第二个值都相同(也是键),因此它给出了具有最大第一个值的元组。列表理解用于根据这些函数的输出形成元组的输出列表。
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.
可能使用字典:
Probably using a dict:
您可以使用以元组的第二个元素为键的字典:
You could use a dictionary keyed on the second element of the tuple: