Index Minimum Value Record in Tuple List
เมื่อต้องการหา Tuple ที่มีค่าน้อยที่สุดใน Column เฉพาะ (แล้วคืนค่า Column อื่น) ใช้ min() และ operator.itemgetter
ตัวอย่างโค้ด
from operator import itemgetter
my_list = [('Will', 45), ('Jam', 13), ('Pow', 89), ('Nyk', 56)]
print("The list is: ")
print(my_list)
# หา Tuple ที่ Index 1 (Score) น้อยที่สุด แล้วเอา Index 0 (Name)
my_result = min(my_list, key=itemgetter(1))[0]
print("The value with minimum score is : ")
print(my_result)
ผลลัพธ์
The list is: [('Will', 45), ('Jam', 13), ('Pow', 89), ('Nyk', 56)]
The value with minimum score is : Jam
คำอธิบาย
- Import
itemgetterจากoperator - กำหนด List of Tuples (Name, Score) และแสดงผล
min(my_list, key=itemgetter(1))หา Tuple ที่ Index 1 น้อยที่สุด- ผลลัพธ์คือ Tuple ทั้งคู่
('Jam', 13) [0]เอาเฉพาะ Index 0 (Name) → 'Jam'- แสดงผล
itemgetter vs Lambda
# ทั้งคู่เทียบเท่ากัน
min(my_list, key=itemgetter(1))
min(my_list, key=lambda x: x[1])
# itemgetter เร็วกว่าเล็กน้อย (C Implementation)
หา Record ที่มีค่าสูงสุด (Max)
max_record = max(my_list, key=itemgetter(1))
print(max_record) # ('Pow', 89)
print(max_record[0]) # 'Pow'
หา Index ของ Record (ใน List)
# หา Index ใน List
min_idx = min(range(len(my_list)), key=lambda i: my_list[i][1])
print(min_idx) # 1 (Index ของ 'Jam')
# หรือ
min_tuple = min(my_list, key=itemgetter(1))
min_idx = my_list.index(min_tuple)
print(min_idx) # 1
หลาย Column (Multi-key Sort)
# เรียงตาม Score แล้วตาม Name
my_list = [('Will', 45, 'A'), ('Jam', 13, 'B'), ('Pow', 13, 'A'), ('Nyk', 56, 'C')]
# Key เป็น Tuple: (Score, Name)
result = min(my_list, key=lambda x: (x[1], x[2]))
print(result) # ('Pow', 13, 'A') - Score เท่ากัน เรียง Name A ก่อน B
ใช้ NumPy
import numpy as np
arr = np.array(my_list, dtype=object)
scores = arr[:, 1].astype(int)
min_idx = np.argmin(scores)
print(arr[min_idx, 0]) # Jam