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, 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. · 点击“运行”查看此处输出。