我需要找到最大值,例如:
[(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中实现这一目标?
任何建议!谢谢你的帮助
答案 0 :(得分:3)
仅使用基础知识:
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
或
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
答案 1 :(得分:2)
排序,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
获取一个排序的项目列表,按一些关键函数对它们进行分组(在本例中我们使用operator.itemgetter(0)
),并为您提供一个形式的迭代器:
[(keyfunc_result, [list_of_results...], ... ]