Skip to content · ⁨본문 바로가기⁩

Flatten a nested list · ⁨중첩列表 평탄화 Flatten⁩

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.

한국어

중첩된 목록 평탄화

목록은 정수 와 다른 목록을 포함할 수 있으며, 어떤 깊이까지나 중첩될 수 있습니다: [1, [2, 3], [4, [5, 6]]]. 정수를 순서대로 나열한 단일 평탄한 목록을 반환하십시오: [1, 2, 3, 4, 5, 6].

**재귀(recursion)**가 완벽하게 맞습니다. 각 항목을 순환while: 항목이 목록이면 그 자체를 평탄화하여 결과를 더하고, 그렇지 않으면 정수이므로 직접 더하십시오. 구별하기 위해 isinstance(item, list)을 사용하십시오.

Log in or create account · ⁨로그인 또는 계정 만들기⁩

IGCSE, A-Level & AP