每日一题 【每日一题】平面列表 -Python-20211012

Jack · 2021年10月12日 · 最后由 Jack 回复于 2021年10月13日 · 70 次阅读
本帖已被设为精华帖!
  1. 问题描述: 给定一个列表,该列表中有的元素是列表,有的是整数。将其变成只包含整数的简单列表
  2. 问题示例: 输入: [[1, 1], 2, [1, 1]] 输出: [1, 1, 2, 1, 1]
Jack 将本帖设为了精华贴 10月12日 22:28

参考代码:

class Solution:
    def flatten(self, nestedList):
        stack = [nestedList]
        flatten_list = []
        while stack:
            top = stack.pop()
            if isinstance(top, list):
                for elem in reversed(top):
                    stack.append(elem)
                else:
                    flatten_list.append(top)
        return flatten_list
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册