Skip to content · ⁨ข้ามไปยังเนื้อหา⁩

Flatten a nested list

English

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) เพื่อแยกแยะ

Log in or create account · ⁨เข้าสู่ระบบหรือสร้างบัญชี⁩

IGCSE, A-Level & AP