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

หาค่าสูงสุดของ Column ที่ N จาก List of Tuples ใน Python

Get Maximum of N-th Column from Tuple List

เมื่อต้องการหาค่าสูงสุดของ Column ที่ N (Index N) จาก List of Tuples สามารถใช้ List Comprehension และ max() ได้

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

my_list = [(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]
print("The list is : ")
print(my_list)

N = 2
print("The value of 'N' has been initialized")

# List Comprehension ดึง Element Index N ทุก Tuple แล้วหา Max
my_result = max([sub[N] for sub in my_list])

print("The maximum of Nth column in the list of tuples is : ")
print(my_result)

ผลลัพธ์

The list is : [(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]
The value of 'N' has been initialized
The maximum of Nth column in the list of tuples is : 78

คำอธิบาย

  • กำหนด List of Tuples (แต่ละ Tuple มี 3 Element) และแสดงผล
  • กำหนด N = 2 (Column ที่ 3, Index 2)
  • [sub[N] for sub in my_list] ดึง Element Index 2 ทุก Tuple: [39, 52, 78, 0]
  • max(...) หาค่าสูงสุด = 78
  • แสดงผล

การดู Column ต่างๆ

TupleIndex 0Index 1Index 2
(67, 78, 39)677839
(34, 23, 52)342352
(99, 69, 78)996978 ← Max
(2, 11, 0)2110

ฟังก์ชันครบถ้วน

def max_nth_column(tuple_list, n):
    """Return max value of nth column, with error handling"""
    if not tuple_list:
        return None
    if not all(len(t) > n for t in tuple_list):
        raise ValueError(f"Some tuples don't have index {n}")
    return max(t[n] for t in tuple_list)

# ใช้งาน
print(max_nth_column(my_list, 0))  # 99
print(max_nth_column(my_list, 1))  # 78
print(max_nth_column(my_list, 2))  # 78

หา Min และ Max พร้อมกัน

col_2 = [t[2] for t in my_list]
print(f"Min: {min(col_2)}, Max: {max(col_2)}")  # Min: 0, Max: 78