Python 如何找到最大值?

Python 如何找到最大值?,python,Python,我需要找到最大值,例如: [(12, 0.95), (15, 0.92), (20, 0.90), (12, 0.88), (15, 0.98), (12, 0.89)] 输出将最大值与id对应: [(12, 0.95), (15, 0.98), (20, 0.90)] 如何在python中实现这一点 任何建议!感谢您的帮助排序、groupby和max import itertools import operator data = [(12, 0.95), (15, 0.92), (20,

我需要找到最大值,例如:

[(12, 0.95), (15, 0.92), (20, 0.90), (12, 0.88), (15, 0.98), (12, 0.89)]
输出将最大值与id对应:

[(12, 0.95), (15, 0.98), (20, 0.90)]
如何在python中实现这一点


任何建议!感谢您的帮助

排序、
groupby
max

import itertools
import operator

data = [(12, 0.95), (15, 0.92), (20, 0.90), (12, 0.88), (15, 0.98), (12, 0.89)]
sorted_data = sorted(data)
groups = itertools.groupby(sorted_data, key=operator.itemgetter(0))
result = [max(group) for _, group in groups]
itertools.groupby
获取项目的排序列表,通过一些关键函数对它们进行分组(在本例中,我们使用
操作符.itemgetter(0)
),并为您提供以下形式的迭代器:

[(keyfunc_result, [list_of_results...], ... ]
仅使用基本功能:

data = [(12, 0.95), (15, 0.92), (20, 0.90), (12, 0.88), (15, 0.98), (12, 0.89)]

result_dict = {}
for id_num, value in data:
    result_dict[id_num] = max(value, result_dict.get(id_num, value))

result = sorted(result_dict.items())

print(result)
如果循环中的部分令人困惑,以下是编写它的其他方法:

if id_num in result_dict:
    result_dict[id_num] = max(result_dict[id_num], value)
else:
    result_dict[id_num] = value


到目前为止你试过什么?您在解决此问题时做了哪些尝试?这会产生错误的结果,您需要向
groupby
添加一个键。默认键是identity,因此所有组都有0个元素,因为它们都是不同的。Sec@AlexHall修复请注意,排序已将最大值移动到每个组的最后一项
if id_num in result_dict:
    if value > result_dict[id_num]:
        result_dict[id_num] = value
else:
    result_dict[id_num] = value
if id_num not in result_dict or value > result_dict[id_num]:
    result_dict[id_num] = value
if id_num > result_dict.get(id_num, value):
    result_dict[id_num] = value