我需要找到例如值的最大值:如何找到最大值?
[(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實現這一目標?
任何建議!感謝您的幫助
我需要找到例如值的最大值:如何找到最大值?
[(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實現這一目標?
任何建議!感謝您的幫助
只需使用基礎知識:
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
排序,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...], ... ]
這給出了錯誤的結果,您需要爲'groupby'添加一個鍵。默認鍵是標識,因此所有組都有0個元素,因爲它們都是不同的。 –
拍攝你是對的,我認爲它默認爲'itemgetter(0)'。秒 –
@AlexHall修復 –
你嘗試過什麼到目前爲止?你在解決這個問題上做了哪些嘗試? – Li357