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

วิธี Join List of Lists ใน Python (Flatten List)

มีหลายวิธี Flatten List of Lists:

1. Nested Loops (Straightforward)

L1=[[1,2],[3,4,5],[6,7,8,9]]
flat=[]
for i in L1:
    for j in i:
        flat.append(j)
print(flat)

2. Generator Function

def flatten(lst):
    for i in lst:
        for j in i:
            yield j

L1=[[1,2,3],[4,5],[6,7,8,9]]
flat=flatten(L1)
print(list(flat))

3. itertools.chain (Most Compact)

import itertools
L1=[[1,2,3],[4,5],[6,7,8,9]]
flat=itertools.chain.from_iterable(L1)
print(list(flat))

ผลลัพธ์ทั้งหมด

[1, 2, 3, 4, 5, 6, 7, 8, 9]