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

如何合并可迭代对象并仅保留各索引位置的首个出现元素?

提取各索引位置首次出现的元素

给定可迭代对象列表:

[[1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13, 14]]

需求是:对每个索引位置,取第一个在该索引存在元素的子列表中的对应元素,最终预期结果为:

[1, 2, 5, 6, 14]

可视化说明:

[1, 2]          # 索引0、1的首次元素来自此列表
[_, _, 5, 6]    # 索引2、3的首次元素来自此列表(前两个索引已有元素,跳过)
[_, _, _]       # 所有索引均已找到元素,跳过
[_, _, _, _, 14]# 索引4的首次元素来自此列表

解决方法

方法一:按索引遍历查找

先确定最长子列表的长度,然后对每个索引,依次检查所有子列表,找到第一个包含该索引的子列表,提取对应元素:

lists = [[1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13, 14]]
max_length = max(len(lst) for lst in lists)
result = []

for idx in range(max_length):
    for sublist in lists:
        if idx < len(sublist):
            result.append(sublist[idx])
            break

print(result)  # 输出: [1, 2, 5, 6, 14]

方法二:用itertools.zip_longest简化

利用zip_longest将所有子列表按位置对齐,每个位置会得到一个包含对应元素的元组(缺失位置用None填充),然后对每个元组取第一个非None的元素:

from itertools import zip_longest

lists = [[1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13, 14]]
# 列表推导式版本
result = [next(elem for elem in group if elem is not None) for group in zip_longest(*lists)]

print(result)  # 输出: [1, 2, 5, 6, 14]

或者展开循环更清晰:

from itertools import zip_longest

lists = [[1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13, 14]]
result = []

for position_group in zip_longest(*lists):
    # 遍历当前位置的所有元素,取第一个非空的
    for elem in position_group:
        if elem is not None:
            result.append(elem)
            break

print(result)  # 输出: [1, 2, 5, 6, 14]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 15:30:57