ลิสต์เป็นคอนเทนเนอร์สำคัญที่ใช้ในทุกๆ โค้ดของการเขียนโปรแกรมประจำวันและพัฒนาเว็บ ยิ่งใช้มากเท่าไหร่ ความรู้ในการดำเนินการกับมันก็ยิ่งจำเป็น
ตัวอย่างโค้ด
1. ใช้ itertools.zip_longest
from itertools import zip_longest
# เริ่มต้น list of lists
test_list = [
[('11'), ('12'), ('13')],
[('21'), ('22'), ('23')],
[('31'), ('32'), ('33')]
]
print("Initial List =", test_list)
# วนลูป list of tuples list of list เป็น single list
res_list = [item for my_list in zip_longest(*test_list) for item in my_list if item]
print("Resultant List =", res_list)
2. ใช้ itertools.zip_longest + lambda + chain
from itertools import zip_longest, chain
test_list = [
[('11'), ('12'), ('13')],
[('21'), ('22'), ('23')],
[('31'), ('32'), ('33')]
]
print("Initial List =", test_list)
# ใช้ lambda + chain + filter
res_list = list(filter(lambda x: x, chain(*zip_longest(*test_list))))
print("Resultant List =", res_list)
3. ใช้ List Comprehension (วิธีง่ายที่สุด)
test_list = [
[('11'), ('12'), ('13')],
[('21'), ('22'), ('23')],
[('31'), ('32'), ('33')]
]
print("Initial List =", test_list)
# ใช้ list comprehension
res_list = [item for list2 in test_list for item in list2]
print("Resultant List =", res_list)
สรุป
- zip_longest - เหมาะเมื่อ sublists มีความยาวไม่เท่ากัน จะเติม None ให้อัตโนมัติ
- chain + filter - รวมการ flatten และกรองค่า None ในขั้นตอนเดียว
- List Comprehension - วิธีที่อ่านง่ายและเร็วที่สุดสำหรับกรณีทั่วไปที่ sublists มีขนาดเท่ากัน