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

Find Maximum Value in Each Sublist ใน Python: หาค่าสูงสุดของแต่ละสับลิสต์

ได้ลิสต์ของลิสต์ หาค่าสูงสุดในแต่ละสับลิสต์

วิธี 1: List Comprehension กับ max()

Alist = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]
res = [max(sub) for sub in Alist]
print(res)  # [454, 23]

วิธี 2: ใช้ map(max, ...)

Alist = [[10, 13, 454, 66, 44], [10, 8, 7, 23]]
res = list(map(max, Alist))
print(res)  # [454, 23]

สรุป

ทั้งคู่เทียบเท่า map เป็น Functional Style list comprehension อ่านง่ายกว่าและ Pythonic กว่า