Flatten a nested list
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.
Flatten ลิสต์ซ้อน
ลิสต์สามารถเก็บ integer และ ลิสต์อื่น, ซ้อนกันได้หลายระดับ: [1, [2, 3], [4, [5, 6]]]. Return one flat list ของ integers ตามลำดับ: [1, 2, 3, 4, 5, 6]
Recursion เหมาะสมอย่างยิ่ง. Loop ผ่านแต่ละ item: ถ้ามันเป็นลิสต์, flatten มัน และเพิ่มผลลัพธ์; มิฉะนั้นมันเป็น integer, ดังนั้นเพิ่มมันโดยตรง. ใช้ isinstance(item, list) เพื่อแยกแยะ
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. · เขียน flatten(nested):给定一个可能包含嵌套整数列表的列表(任意深度),返回一个扁平化的单个整数列表,保持顺序。使用递归。
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่