Multiply Adjacent Elements ใน Tuple
เมื่อต้องการคูณเอลีเมนต์ที่อยู่ติดกันใน Tuple สามารถใช้เมธอด zip(), tuple() และ Generator Expression ได้
การทำงานของ zip()
zip() รับ iterables มารวมกันเป็น Tuple คืนค่าเป็น Iterator ของ Tuple
Generator คืออะไร?
Generator เป็นวิธีสร้าง Iterator อย่างง่าย โดยอัตโนมัติ implement __iter__() และ __next__() รวมถึงจัดการสถานะภายในและ raise StopIteration เมื่อไม่มีค่าเหลือ
ตัวอย่างโค้ด
my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22)
print("The tuple is : ")
print(my_tuple_1)
# zip กับ tuple เดียวกันแต่ข้ามตัวแรกไป
my_result = tuple(i * j for i, j in zip(my_tuple_1, my_tuple_1[1:]))
print("The tuple after multiplication is : ")
print(my_result)
ผลลัพธ์
The tuple is : (7, 8, 0, 3, 45, 3, 2, 22) The tuple after multiplication is : (56, 0, 0, 135, 135, 6, 44)
คำอธิบาย
- กำหนด Tuple และแสดงผล
- ใช้
zip()รวม Tuple เดียวกันกับ Tuple เดียวกันที่ข้ามตัวแรก (my_tuple_1[1:]) - วนลูปคูณค่าที่ตรงกัน (i * j)
- แปลงผลลัพธ์เป็น Tuple
- แสดงผลบนคอนโซล
การคำนวณแบบละเอียด
| Index | Element 1 | Element 2 | ผลคูณ |
|---|---|---|---|
| 0 | 7 | 8 | 56 |
| 1 | 8 | 0 | 0 |
| 2 | 0 | 3 | 0 |
| 3 | 3 | 45 | 135 |
| 4 | 45 | 3 | 135 |
| 5 | 3 | 2 | 6 |
| 6 | 2 | 22 | 44 |