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

การหาค่าสูงสุดใน List of Tuples ด้วย Python

หา Maximum Element ใน List of Tuples

เมื่อต้องการหาเอลีเมนต์ที่มีค่าสูงสุดใน List of Tuples โดยอ้างอิงจาก Column เฉพาะ สามารถใช้ max() ร่วมกับ operator.itemgetter ได้

operator.itemgetter

itemgetter(n) สร้าง Callable ที่ดึง Item ที่ Index n จาก Object ที่ส่งเข้าไป

max()

max(iterable, key=...) หาค่าสูงสุดใน Iterable โดยใช้ Key function กำหนดเกณฑ์การเปรียบเทียบ

ตัวอย่างโค้ด

from operator import itemgetter

my_list = [('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]
print("The list is :")
print(my_list)

# หา Tuple ที่มีค่า Index 1 สูงสุด แล้วเอา Index 0 (ชื่อ)
my_result = max(my_list, key=itemgetter(1))[0]

print("The name that has the maximum value is : ")
print(my_result)

ผลลัพธ์

The list is : [('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]
The name that has the maximum value is : Min

คำอธิบาย

  • Import itemgetter จาก operator
  • กำหนด List of Tuples (ชื่อ, คะแนน) และแสดงผล
  • ใช้ max() พร้อม key=itemgetter(1) เพื่อเปรียบเทียบจาก Column Index 1 (คะแนน)
  • ผลลัพธ์คือ Tuple ทั้งคู่ ('Min', 101) จึงใช้ [0] เอาเฉพาะชื่อ
  • แสดงผลบนคอนโซล

การขยาย: หาค่าสูงสุดของหลาย Column

# หาค่าสูงสุดของแต่ละ Column แยกกัน
scores = [('Will', 23, 85), ('Jane', 21, 90), ('El', 24, 88), ('Min', 101, 95)]

max_score1 = max(scores, key=itemgetter(1))  # คะแนนสูงสุด
max_score2 = max(scores, key=itemgetter(2))  # คะแนนสอบสูงสุด

print("Max by score1:", max_score1)
print("Max by score2:", max_score2)

หาค่าสูงสุดของ Column โดยไม่ใช้ itemgetter (Lambda)

my_result = max(my_list, key=lambda x: x[1])[0]
# เทียบเท่ากับ itemgetter(1)