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

Python中将三层嵌套列表[[[1],[1],[1]]]降维为一维列表的简便方法咨询

方案1:使用numpy(你现有代码已经引入numpy,最简便)

直接一行代码完成转换:

import numpy as np
d = [[[1],[1],[1]]]
res = np.array(d).flatten().tolist()
print(res) # 输出 [1, 1, 1]

方案2:原生Python固定层数嵌套(无需第三方库)

针对你这种3层嵌套的结构,用列表推导式一行搞定:

d = [[[1],[1],[1]]]
res = [x for layer1 in d for layer2 in layer1 for x in layer2]
print(res) # 输出 [1, 1, 1]

如果是2层/4层嵌套,对应调整推导式的循环层数即可。

方案3:通用任意层数嵌套展平

如果不确定嵌套层数,写个递归函数通用处理:

def flatten_list(lst):
    result = []
    for item in lst:
        if isinstance(item, list):
            result.extend(flatten_list(item))
        else:
            result.append(item)
    return result

d = [[[1],[1],[1]]]
res = flatten_list(d)
print(res) # 输出 [1, 1, 1]

补充小技巧

对于层数很少的嵌套,也可以用sum嵌套快速展平,3层嵌套的写法如下:

d = [[[1],[1],[1]]]
res = sum(sum(d, []), [])
print(res) # 输出 [1, 1, 1]

该方法仅适合低层数嵌套,层数过高时性能和可读性都很差,不推荐使用。

内容的提问来源于stack exchange,提问作者Seungjun Lee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 19:27:03