Maximum Value in Record List as Tuple Attribute
เมื่อต้องการหาค่าสูงสุดใน List ที่อยู่ภายใน Tuple Attribute ของแต่ละ Record ใช้ List Comprehension และ max()
ตัวอย่างโค้ด
my_list = [('Will', [67, 45, 89]), ('Jam', [34, 56, 13]), ('Pow', [99, 123, 89]), ('Nyk', [0, 56, 5])]
print("The list of tuples is : ")
print(my_list)
# List Comprehension: สำหรับแต่ละ (key, lst) หา max(lst)
my_result = [(key, max(lst)) for key, lst in my_list]
print("The maximum of list tuple attribute is : ")
print(my_result)
ผลลัพธ์
The list of tuples is : [('Will', [67, 45, 89]), ('Jam', [34, 56, 13]), ('Pow', [99, 123, 89]), ('Nyk', [0, 56, 5])]
The maximum of list tuple attribute is : [('Will', 89), ('Jam', 56), ('Pow', 123), ('Nyk', 56)]
คำอธิบาย
- กำหนด List of Tuples: (Name, [List of Scores]) และแสดงผล
- List Comprehension Unpack:
for key, lst in my_list - หา
max(lst)ของแต่ละ List ภายใน - สร้าง Tuple ใหม่ (Name, MaxScore)
- แสดงผล
การทำงานแบบละเอียด
| Record | Name | Scores | Max |
|---|---|---|---|
| 1 | Will | [67, 45, 89] | 89 |
| 2 | Jam | [34, 56, 13] | 56 |
| 3 | Pow | [99, 123, 89] | 123 |
| 4 | Nyk | [0, 56, 5] | 56 |
ขยาย: หา Min, Max, Average พร้อมกัน
from statistics import mean
my_result = [(key, min(lst), max(lst), round(mean(lst), 2)) for key, lst in my_list]
print(my_result)
# [('Will', 45, 89, 67.0), ('Jam', 13, 56, 34.33), ('Pow', 89, 123, 103.67), ('Nyk', 0, 56, 20.33)]
กรณี List ว่าง (Error Handling)
my_list = [('A', [1, 2]), ('B', []), ('C', [3])]
def safe_max(lst):
return max(lst) if lst else None
result = [(key, safe_max(lst)) for key, lst in my_list]
print(result) # [('A', 2), ('B', None), ('C', 3)]
ใช้ Map + Lambda
result = list(map(lambda x: (x[0], max(x[1])), my_list))
print(result) # [('Will', 89), ('Jam', 56), ('Pow', 123), ('Nyk', 56)]