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.

日本語

多次元リストをフラット化する

リストは整数や他のリストを、任意の深さまでネストして保持できます: [1, [2, 3], [4, [5, 6]]] 。整数だけを順に並べた1つのフラットなリストを返します: [1, 2, 3, 4, 5, 6] 。

再帰が完璧に合います。各要素をループで巡ります: リストならそれをフラット化して結果を追加し、整数なら直接追加します。isinstance(item, list) で区別します。

Log in or create account · ⁨ログインまたはアカウント作成⁩

IGCSE, A-Level & AP