เมื่อต้องการหาผลรวมแบบสลับคู่ (alternate summation) ของลิสต์ tuple คู่ สามารถใช้ลูป iteration และตัวดำเนินการ modulus ได้
ตัวอย่าง
my_list = [(24, 11), (45, 66), (53, 52), (77, 51), (31, 10)]
print("The list is :")
print(my_list)
my_result = 0
for index in range(len(my_list)):
if index % 2 == 0:
my_result += my_list[index][0]
else:
my_result += my_list[index][1]
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [(24, 11), (45, 66), (53, 52), (77, 51), (31, 10)] The result is : 225
คำอธิบาย
กำหนดลิสต์ของ tuple คู่ตัวเลข ตัวแปรผลรวมเริ่มต้น 0
วนลูปดัชนี ถ้าดัชนีคู่ (index % 2 == 0) บวกสมาชิกตัวแรก [0] ถ้าคี่ บวกสมาชิกตัวที่สอง [1]
คำนวณ: 24 + 66 + 53 + 51 + 31 = 225
แสดงผลลัพธ์