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, 2, 3, 4, 5, 6]。

递归非常适合。遍历每个元素:如果它是列表,就展平它并把结果加入;否则它是整数,直接加入。用 isinstance(item, list) 来区分两者。

Log in or create account · ⁨登录或创建账户⁩

IGCSE, A-Level · ⁨IGCSE、A-Level⁩ & AP · ⁨与 AP⁩