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

แปลง nested list เป็น flat list ใน Python

Nested list คือลิสต์ที่สมาชิกเป็นลิสต์อีก ทำให้ต้อง flatten ให้เป็นลิสต์แบน ใช้ recursion

ตัวอย่าง

listA = [[43, [0]], 12, 19, [13, [8, 8]], 21]
print('Given nested list: \n', listA)
res = []
def flatlist(l):
    for x in l:
        if type(x) == list:
            flatlist(x)
        else:
            res.append(x)
flatlist(listA)
print('Flattened List created: \n', res)

ผลลัพธ์

Given nested list: [[43, [0]], 12, 19, [13, [8, 8]], 21]
Flattened List created: [43, 0, 12, 19, 13, 8, 8, 21]