You need to enable JavaScript to run this app. 如何匹配list与dict类型变量中的数据并输出合并结果
优惠活动
大模型
产品
解决方案
定价
更多

如何匹配list与dict类型变量中的数据并输出合并结果

代码问题分析

  • 匹配逻辑错误:原判断条件if v in [info]完全不成立,你需要匹配的是文档编号是否存在于对应货架的编号列表中,而非将整个列表和单条文档对象做包含判断
  • 语法错误:k([info['number']])将字符串类型的货架号k当作函数调用,会直接触发类型报错
  • 数据格式不兼容:directories中存储的第一个编号为2207_876234,和documents中对应编号的空格格式不一致,需要先做格式统一处理

实现代码

documents = [
    {'type': 'passport', 'number': '2207 876234', 'name': 'Smith'},
    {'type': 'invoice', 'number': '11-2', 'name': 'Obama'}, 
    {'type': 'insurance', 'number': '10006', 'name': 'Carpenter'}
]
directories = {'1': ['2207_876234', '11-2'], '2': ['10006'], '3': ['0']}

# 提前构建编号到货架号的映射,统一处理下划线/空格格式差异
num_shelf_map = {}
for shelf_id, num_list in directories.items():
    for num in num_list:
        # 把下划线替换为空格和documents的编号格式对齐
        formatted_num = num.replace('_', ' ')
        num_shelf_map[formatted_num] = shelf_id

result_items = []
for doc in documents:
    doc_num = doc['number']
    # 跳过没有匹配到货架的记录
    if doc_num not in num_shelf_map:
        continue
    result_items.append(f"№: {doc_num}, type: {doc['type']}, owner: {doc['name']}, shelf number: {num_shelf_map[doc_num]}")

# 合并为单行输出
print(' '.join(result_items))

运行输出

№: 2207 876234, type: passport, owner: Smith, shelf number: 1 №: 11-2, type: invoice, owner: Obama, shelf number: 1 №: 10006, type: insurance, owner: Carpenter, shelf number: 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 03:30:00