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

วิธีทำ Flat List จาก List of Lists ใน Python

เมื่อมีลิสต์ที่สมาชิกแต่ละตัวก็เป็นลิสต์ (nested list) การรวมสมาชิกทั้งหมดเข้าเป็นลิสต์เดียวเรียกว่า "Flat List" หรือ "Flattening"

วิธีที่ 1: ใช้ List Comprehension (แนะนำ)

nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
print(flat)  # [1, 2, 3, 4, 5, 6]

วิธีที่ 2: ใช้ itertools.chain

import itertools
nested = [[1, 2], [3, 4], [5, 6]]
flat = list(itertools.chain.from_iterable(nested))
print(flat)  # [1, 2, 3, 4, 5, 6]

วิธีที่ 3: ใช้ sum() (ไม่แนะนำสำหรับลิสต์ใหญ่)

nested = [[1, 2], [3, 4], [5, 6]]
flat = sum(nested, [])
print(flat)  # [1, 2, 3, 4, 5, 6]

วิธีที่ 4: ใช้ reduce() (Python 3 ต้อง import จาก functools)

from functools import reduce
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda x, y: x + y, nested)
print(flat)  # [1, 2, 3, 4, 5, 6]

ประสิทธิภาพ: List comprehension และ itertools.chain เร็วที่สุดและ Pythonic ที่สุด