简体   繁体   English

在第一个元素相同的所有值中找到第二个元素最大的元组

[英]Find those tuples in which the second element is maximum among all values with same first element

How to sanitize a given list of tuples, such that only tuples with maximum values are listed. 如何清理给定的元组列表,以便仅列出具有最大值的元组。

mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]

Result 结果

[('a',6), ('b', 10), ('c', 8), ('d', 12)]

Turn it into a dictionary: 把它变成字典:

mytup = [('a',2),('a',6),('b',4),('a',4),('b',10),('c',4),('c',6),('c',8),('d',12),('d',10)]
d = {}

for key, value in mytup:
    if d.get(key) < value:  # d.get(key) returns None if the key doesn't exist
        d[key] = value      # None < float('-inf'), so it'll work

result = d.items()

I think this should work: 我认为这应该工作:

dict = {}
for key, val in mytup:
    try:
        if dict[key] < val:
            dict[key] = val
    except IndexError:
        dict[key] = val

Itertools is your friend, one line solution: Itertools是您的朋友,一线解决方案:

from itertools import groupby
print [ max(g) for _, g in groupby(sorted(mytup), lambda x: x[0] )]

Results: 结果:

[('a', 6), ('b', 10), ('c', 8), ('d', 12)]

暂无
暂无

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

相关问题 检查元组列表中元组的第二个元素是否都相同 - check if the second element of tuples in list of tuples are all the same 具有元组键的字典:所有具有相同第一个元素的元组 - Dictionary with tuples key: All tuples with the same first element 引用元组列表中所有元组的第一个元素 - Referring to the first element of all tuples in a list of tuples Python按第一和第二个元素对元组进行排序 - Python sorting tuples by first and second element 给定一个元组列表,如果第一个元素相同,我如何在每个相似的元组中添加第二个元素 - Given a list of tuples, if the first element is the same, how do i add the second element inside each similar tuple 根据第一个元素搜索元组列表并获取第二个元素值列表 - Search list of tuples according to first element and get list of second element values 我有 2 个元组列表,如何打印元组的第二个元素之间的差异,同时让第一个元素保持不变? - I have 2 lists of tuples, how can I print the difference between the second element of the tuples while leaving the first element the same? 我想追加到新列表中,仅添加第三个元素与第一个元素的第三个元素相同的元组 - I want to append to a new list , only the tuples in which the third element is the same with the third element of the first tuple 如何有效地为多个矩阵中的每个元素分别找到 N 个最大值? - How to efficiently find separately for each element N maximum values among multiple matrices? 按第二个元素分组元组列表,取第一个元素的平均值 - Group list-of-tuples by second element, take average of first element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM