ลิสต์เป็นคอลเลกชันที่มีลำดับและเปลี่ยนแปลงได้ เขียนด้วยวงเล็บเหลี่ยม เข้าถึงได้โดยดัชนี โดย -1 คือตัวสุดท้าย สามารถ slice ได้เพื่อดึงช่วงข้อมูล
ตัวอย่างโค้ด
1. ใช้ itertools.chain.from_iterable (แนะนำสำหรับประสิทธิภาพ)
from itertools import chain
ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
print("initial list", str(ini_list))
flatten_list = list(chain.from_iterable(ini_list))
print("final_result", str(flatten_list))
2. ใช้ List Comprehension (Pythonic และอ่านง่าย)
ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
print("initial list", str(ini_list))
flatten_list = [j for sub in ini_list for j in sub]
print("final_result", str(flatten_list))
3. ใช้ functools.reduce
from functools import reduce
ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
print("initial list", str(ini_list))
flatten_list = reduce(lambda z, y: z + y, ini_list)
print("final_result", str(flatten_list))
4. ใช้ sum() (สั้นแต่ช้าสำหรับลิสต์ใหญ่)
ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
print("initial list", str(ini_list))
flatten_list = sum(ini_list, [])
print("final_result", str(flatten_list))
5. ใช้ Lambda แบบ Recursive (สำหรับ nested list ลึก)
ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]]
flatten_list = lambda y: [x for a in y for x in flatten_list(a)] if type(y) is list else [y]
print("Initial list", ini_list)
print("Flattened List", flatten_list(ini_list))
ผลลัพธ์
[1, 2, 3, 3, 6, 7, 7, 5, 4]
สรุปและแนะนำ
| วิธี | ข้อดี | ข้อควรระวัง |
|---|---|---|
| chain.from_iterable | เร็วที่สุด หน่วยความจำน้อย สำหรับลิสต์ใหญ่ | ต้อง import itertools |
| List Comprehension | อ่านง่าย Pythonic ไม่ต้อง import | สร้างลิสต์ใหม่ในหน่วยความจำ |
| reduce | Functional style | ช้ากว่า chain สร้างลิสต์กลางมาก |
| sum() | โค้ดสั้นที่สุด | ช้ามาก O(n²) ไม่แนะนำสำหรับลิสต์ใหญ่ |
| Recursive lambda | รองรับ nested list หลายชั้น | ซับซ้อน อาจเกิน recursion limit |
สำหรับ Nested List หลายชั้น (Deep Flatten)
from itertools import chain
def deep_flatten(lst):
for item in lst:
if isinstance(item, list):
yield from deep_flatten(item)
else:
yield item
nested = [[1, [2, 3]], [4, 5], 6]
print(list(deep_flatten(nested))) # [1, 2, 3, 4, 5, 6]