Flatten a nested list · Dẹt hóa danh sách lồng nhau
Flatten a nested list
A list can hold integers and other lists, nested to any depth: [1, [2, 3], [4, [5, 6]]]. Return one flat list of the integers in order: [1, 2, 3, 4, 5, 6].
Recursion fits perfectly. Loop over each item: if it's a list, flatten it and add the results; otherwise it's an integer, so add it directly. Use isinstance(item, list) to tell them apart.
Phẳng hóa danh sách lồng nhau
Một danh sách có thể chứa số nguyên và các danh sách khác, lồng nhau bất kỳ độ sâu nào: [1, [2, 3], [4, [5, 6]]]. Trả về một danh sách phẳng chứa các số nguyên theo thứ tự: [1, 2, 3, 4, 5, 6].
Đệ quy phù hợp hoàn hảo. Lặp qua từng mục: nếu nó là danh sách, phẳng hóa nó và thêm các kết quả; ngược lại nó là số nguyên, nên thêm trực tiếp. Sử dụng isinstance(item, list) để phân biệt chúng.
Write flatten(nested): given a list that may contain nested lists of integers (any depth), return a single flat list of the integers, in order. Use recursion. · Viết flatten(nested): nhận một danh sách có thể chứa danh sách lồng nhau của số nguyên (bất kỳ độ sâu nào), trả về một danh sách phẳng duy nhất của các số nguyên, theo thứ tự. Sử dụng đệ quy.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.