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

遍历两个列表配对,缺失对应键时在正确位置插入None

问题解决:按配对位置匹配字典键并补全None

需求说明

给定映射字典stuff_types和两个等长列表a、b,需要按(a[i], b[i])的配对位置生成结果列表:

  • 若配对中任意一个元素是stuff_types的键,就将对应字典值加入结果
  • 若配对中两个元素都不在字典键中,就在该位置插入None

期望结果:

[{'type': 'POT'}, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]

错误代码分析

之前的代码会遍历配对中的每个元素单独判断,导致结果长度是原配对数的2倍,不符合需求:

stuff_types = {
    "spana": {"type": "BOOK"},
    "geom": {"type": "GLASS"},
    "hlian": {"type": "POT"}
}

a = ['kal', 'khp', 'khp', 'khp', 'geom']
b = ['hlian', 'spana', 'piper', 'meli', 'phin']

the_list = []
for tup in zip(a, b):
    for x in tup:
        if x in stuff_types:
            the_list.append(stuff_types[x])
        else:
             the_list.append(None)
            
print(the_list)

正确实现代码

调整逻辑,对每个配对只做一次判断,优先检查第一个元素,再检查第二个:

stuff_types = {
    "spana": {"type": "BOOK"},
    "geom": {"type": "GLASS"},
    "hlian": {"type": "POT"}
}

a = ['kal', 'khp', 'khp', 'khp', 'geom']
b = ['hlian', 'spana', 'piper', 'meli', 'phin']

the_list = []
for x, y in zip(a, b):
    if x in stuff_types:
        the_list.append(stuff_types[x])
    elif y in stuff_types:
        the_list.append(stuff_types[y])
    else:
        the_list.append(None)

print(the_list)

运行后输出符合期望的结果:

[{'type': 'POT'}, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:48:29