You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用循环实现Python未知嵌套层级列表的扁平化?

未知嵌套层级列表扁平化问题

问题描述

输入为任意嵌套层级的列表,示例输入:

[    [1, 2],    [        3,        [4, 5],    ],    6,    7,]

需要将其转换为单层级列表,示例输出:

[1, 2, 3, 4, 5, 6, 7]

现有代码及报错

你编写的代码如下:

import json
data = json.loads(input())
#WRITE YOUR CODE HERE 
list_data = list(data) 
flat_list = [item for items in list_data for item in items] 
print(flat_list)

运行触发错误:TypeError: 'int' 对象不可迭代

报错原因

你的列表推导式仅能处理一层嵌套。当遍历到6、7这类整数元素,或者嵌套子列表中的非列表元素时,for item in items会尝试迭代整数,但整数不是可迭代对象,因此抛出该错误。

循环实现的解决方案

要处理未知层级的嵌套,需要遍历每个元素并判断是否为列表,若是则继续深入处理,否则直接加入结果列表。以下是两种基于循环的实现方式:

方式1:栈实现(纯迭代循环)

import json

def flatten_list(nested_list):
    flat_list = []
    stack = [nested_list]
    while stack:
        current = stack.pop()
        for item in current:
            if isinstance(item, list):
                stack.append(item)
            else:
                flat_list.append(item)
    # 栈弹出顺序导致结果逆序,反转后得到正确顺序
    return flat_list[::-1]

data = json.loads(input())
print(flatten_list(data))

方式2:递归+循环(逻辑更直观)

import json

def flatten_list(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            # 递归处理子列表,将结果扩展到主列表
            flat_list.extend(flatten_list(item))
        else:
            flat_list.append(item)
    return flat_list

data = json.loads(input())
print(flatten_list(data))

代码说明

  • 栈实现:用栈存储待处理的列表,每次取出列表遍历,遇到子列表就压入栈,遇到非列表元素则加入结果,最后反转结果得到正确顺序,适合处理极深嵌套的场景。
  • 递归+循环:遍历每个元素,若为列表则递归处理并合并结果,否则直接添加元素,逻辑更易理解,适合常规嵌套层级的场景。

内容的提问来源于stack exchange,提问作者Albina Hakobyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:30:57