เมื่อต้องการดึงสับลิสต์ที่ความต่างระหว่างค่าสูงสุดและต่ำสุด (extreme values) มากกว่า K สามารถใช้ list comprehension, min() และ max() ได้
ตัวอย่าง
my_list = [[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]]
print("The list is :")
print(my_list)
key = 40
my_result = [element for element in my_list if max(element) - min(element) > key]
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [[13, 52, 11], [94, 12, 21], [23, 45, 23], [11, 16, 21]] The result is : [[13, 52, 11], [94, 12, 21]]
คำอธิบาย
กำหนดเมทริกซ์และค่า key (เกณฑ์ความต่าง)
ใช้ list comprehension คำนวณ
max(element) - min(element)ของแต่ละแถวเก็บเฉพาะแถวที่ความต่าง > key (40)
แถวแรก: 52-11=41>40, แถวสอง: 94-12=82>40, แถวสาม: 45-23=22≤40, แถวสี่: 21-11=10≤40