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

如何在Python中扁平化嵌套列表并实现结果均匀分布?

Python实现嵌套列表按列扁平化

给定嵌套列表:

[
  [1, 2, 3],
  [4, 5],
  [6, 8, 9, 10],
  [11]
]

需要将其按列优先的规则扁平化,得到结果:[1, 4, 6, 11, 2, 5, 8, 3, 9, 10]。以下是两种可行的实现方式:

方法一:使用itertools.zip_longest

借助itertools模块的zip_longest函数,它会自动对齐不同长度的子列表,缺失位置用None填充,我们只需要过滤掉None即可:

from itertools import zip_longest

nested_list = [
    [1, 2, 3],
    [4, 5],
    [6, 8, 9, 10],
    [11]
]

flattened = []
for col in zip_longest(*nested_list):
    flattened.extend(item for item in col if item is not None)

print(flattened)  # 输出: [1, 4, 6, 11, 2, 5, 8, 3, 9, 10]

方法二:手动遍历索引(无需额外模块)

先计算最长子列表的长度,再按索引逐列遍历所有子列表,收集有效元素:

nested_list = [
    [1, 2, 3],
    [4, 5],
    [6, 8, 9, 10],
    [11]
]

max_length = max(len(sublist) for sublist in nested_list)
flattened = []

for idx in range(max_length):
    for sublist in nested_list:
        if idx < len(sublist):
            flattened.append(sublist[idx])

print(flattened)  # 输出: [1, 4, 6, 11, 2, 5, 8, 3, 9, 10]

两种方法都能实现需求:第一种代码更简洁,第二种无需依赖外部模块,逻辑更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:25:10