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

如何用Python列表推导式批量扁平化多个嵌套列表

解决方法

1. 封装成可复用的函数

把扁平化逻辑封装成函数,之后需要处理任何嵌套列表时直接调用即可,彻底避免重复写相同代码:

def flatten(nested_list):
    return [item for sublist in nested_list for item in sublist]

first = [[1,2,3], [4,5,6], [7,8,9]]
second = [[3,5,6], [0,3,4]]
third = [[2,5,0], [1,2,9]]

flat_first = flatten(first)
flat_second = flatten(second)
flat_third = flatten(third)

如果处理的是大型列表,想追求更高效率,可以用itertools.chain(它返回迭代器,避免一次性生成完整列表占用过多内存):

from itertools import chain

def flatten(nested_list):
    return list(chain.from_iterable(nested_list))

2. 一次性批量处理所有嵌套列表

如果想一次性得到所有列表的扁平化结果,不用逐个调用函数,可以用列表推导式批量生成:

first = [[1,2,3], [4,5,6], [7,8,9]]
second = [[3,5,6], [0,3,4]]
third = [[2,5,0], [1,2,9]]

all_lists = [first, second, third]
flattened_lists = [[item for sublist in lst for item in sublist] for lst in all_lists]

# 解构得到单个扁平化列表
flat_first, flat_second, flat_third = flattened_lists

你之前代码的问题

你写的循环里,每次迭代都会把flattened重新赋值为当前列表的扁平化结果,循环结束后flattened只会保留最后一个列表(也就是third)的扁平化数据,没有保存所有结果。如果想用循环实现,需要把结果存入一个列表:

all_lists = [first, second, third]
flattened_lists = []
for lst in all_lists:
    flattened_lists.append([item for sublist in lst for item in sublist])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:42:43