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

Python - หาความต่างสูงสุดระหว่างสองลิสต์ (Maximum Difference Across Lists)


ตัวอย่าง

โค้ดด้านล่างคำนวณความต่างสัมบูรณ์ระหว่างสมาชิกตำแหน่งเดียวกันของสองลิสต์ แล้วหาค่าสูงสุด

my_list_1 = [7, 9, 1, 2, 7]
my_list_2 = [6, 3, 1, 2, 1]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
my_result = max(abs(my_list_2[index] - my_list_1[index]) for index in range(0, len(my_list_1) - 1))
print("The maximum difference among the lists is :")
print(my_result)

ผลลัพธ์

The first list is : [7, 9, 1, 2, 7]
The second list is : [6, 3, 1, 2, 1]
The maximum difference among the lists is : 6

คำอธิบาย

  • กำหนดสองลิสต์และแสดงผล

  • วนลูปผ่านดัชนี คำนวณความต่างสัมบูรณ์ระหว่างสมาชิกตำแหน่งเดียวกัน

  • ใช้ max() หาค่าความต่างสูงสุด

  • แสดงผลลัพธ์