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

Python如何合并嵌套可变长度附件列表与邮件ID列表?

错误原因分析

你使用itertools.chain时出现拆分错误,是因为字符串(比如邮件ID'c1')属于可迭代对象,chain会默认将其拆分为单个字符,不符合你的拼接需求,这个方法不适用于当前场景。

另外你给出的预期输出中出现的c4属于笔误,按照输入的邮件ID列表b的规则,对应第三个邮件的ID应为c3,以下方案基于修正后的逻辑输出。


实现代码

1. 按邮件分组的嵌套格式(完全匹配你要求的输出结构)

a = [[], ['a'], ['b', 'c', 'd']]
b = ['c1', 'c2', 'c3']

result = []
for mail_id, attachments in zip(b, a):
    # 跳过无附件的邮件记录
    if not attachments:
        continue
    # 为当前邮件的每个附件生成[邮件ID, 文件名]的配对
    current_group = [[mail_id, file] for file in attachments]
    result.append(current_group)

输出结果:

[[['c2', 'a']], [['c3', 'b'], ['c3', 'c'], ['c3', 'd']]]

也可以用列表推导式简化为一行:

result = [[[mail_id, file] for file in attachments] for mail_id, attachments in zip(b, a) if attachments]

2. 平展格式(更适合后续入库使用)

如果不需要按邮件分组,直接生成所有附件的配对列表,使用以下代码:

result = []
for mail_id, attachments in zip(b, a):
    if not attachments:
        continue
    for file in attachments:
        result.append([mail_id, file])

输出结果:

[['c2', 'a'], ['c3', 'b'], ['c3', 'c'], ['c3', 'd']]

列表推导式版本:

result = [[mail_id, file] for mail_id, attachments in zip(b, a) if attachments for file in attachments]

方案优势

不需要引入额外依赖,遍历一次即可完成处理,时间复杂度为O(n)(n为附件总数),处理数千条记录效率极高,不存在ID和文件名匹配错误的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:45:03