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.
多次元リストをフラット化する
リストは整数や他のリストを、任意の深さまでネストして保持できます: [1, [2, 3], [4, [5, 6]]] 。整数だけを順に並べた1つのフラットなリストを返します: [1, 2, 3, 4, 5, 6] 。
再帰が完璧に合います。各要素をループで巡ります: リストならそれをフラット化して結果を追加し、整数なら直接追加します。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. · 実行ボタンをクリックして出力を確認してください。