Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Get First Element with Maximum Value ใน List of Tuples Python

ได้ลิสต์ของ Tuple ต้องการ Tuple ที่มีค่า (index 1) สูงสุด หากมีหลาย Tuple ค่าเท่ากัน ให้ Tuple แรกที่เจอ

วิธี 1: max() กับ operator.itemgetter(1)

from operator import itemgetter
listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
res = max(listA, key=itemgetter(1))[0]
print(res)  # Tue

วิธี 2: max() กับ lambda

listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
res = max(listA, key=lambda x: x[1])[0]
print(res)  # Tue

วิธี 3: sorted() แบบ Descending

listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
res = sorted(listA, key=lambda x: x[1], reverse=True)[0][0]
print(res)  # Tue

สรุป

ทุกวิธีคืน 'Tue' เพราะมีค่า 20 สูงสุด max() คืนตัวแรกที่เจอเมื่อค่าเท่ากัน sorted() คงลำดับเดิม (stable sort)