问题描述
给定一个列表,该列表中有的元素是列表,有的元素是整数。将这个列表变成只包含整数的简单列表。
示例
输入 [[3, 4], 2] ,输出 [3, 4, 2] ;输入 [1, [2, 5], 0] ,输出 [1, 2, 5, 0] ;输入 [[[4, 3], 4], 8] ,输出 [4, 3, 4, 8] ,即将输入列表变成只包含整数的简单列表。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def flatten(List): a = [List] flatten_list = [] while a: top = a.pop() if isinstance(top, list): for i in reversed(top): a.append(i) else: flatten_list.append(top) return flatten_list alist = [[[3, 2], 6]] print("输入:", alist) print("输出:", flatten(alist)) |
运行结果
1 2 |
输入: [[[3, 2], 6]] 输出: [3, 2, 6] |