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

Python:合并两列表并按字典type匹配去重,生成指定结构数据

问题:合并列表并转换为指定结构

需求说明

  • 合并两个列表cats和types,匹配对应数据并转换为指定的新结构
  • 现有数据:
    cats = [
        'orange', 'apple', 'banana'
    ]
    
    types = [
        {"id": 1, "type": "orange"},
        {"id": 2, "type": "apple"},
        {"id": 3, "type": "apple"},
        {"id": 4, "type": "orange"},
        {"id": 5, "type": "banana"}
    ]
    
  • 期望输出:
    [
        {'orange': {'UNIT': [1, 4]}},
        {'apple': {'UNIT': [2, 3]}},
        {'banana': {'UNIT': [5]}}
    ]
    

现有代码问题

现有代码运行后结果不符合预期,每个条目包含所有id且存在重复:

现有代码

matched = []
for item in types:
    for cat in cats:
        if item['type'] == cat:
            matched.append(
                {
                    cat: {
                        "UNIT": [i['id'] for i in types if 'id' in i]
                    }
                }
            )

错误输出

[{'orange': {'UNIT': [1, 2, 3, 4, 5]}},
 {'apple': {'UNIT': [1, 2, 3, 4, 5]}},
 {'apple': {'UNIT': [1, 2, 3, 4, 5]}},
 {'orange': {'UNIT': [1, 2, 3, 4, 5]}},
 {'banana': {'UNIT': [1, 2, 3, 4, 5]}}]

问题根源

  1. 每次匹配到对应类型时,代码会遍历整个types列表收集所有id,而非仅当前类型的id
  2. 每匹配到一个types中的条目就往matched里添加一次,导致出现重复条目

修正后的代码

提供两种简洁的实现方式:

方式一:先按类型分组id,再生成目标结构

cats = ['orange', 'apple', 'banana']
types = [
    {"id": 1, "type": "orange"},
    {"id": 2, "type": "apple"},
    {"id": 3, "type": "apple"},
    {"id": 4, "type": "orange"},
    {"id": 5, "type": "banana"}
]

# 先按type分组收集对应id
type_id_map = {}
for item in types:
    t = item['type']
    if t not in type_id_map:
        type_id_map[t] = []
    type_id_map[t].append(item['id'])

# 生成目标结构
matched = []
for cat in cats:
    matched.append({cat: {'UNIT': type_id_map.get(cat, [])}})

print(matched)

方式二:直接遍历cats,筛选对应id

cats = ['orange', 'apple', 'banana']
types = [
    {"id": 1, "type": "orange"},
    {"id": 2, "type": "apple"},
    {"id": 3, "type": "apple"},
    {"id": 4, "type": "orange"},
    {"id": 5, "type": "banana"}
]

matched = []
for cat in cats:
    # 筛选当前cat对应的所有id
    ids = [item['id'] for item in types if item['type'] == cat]
    matched.append({cat: {'UNIT': ids}})

print(matched)

最终输出结果

两种方式都会得到预期的输出:

[
    {'orange': {'UNIT': [1, 4]}},
    {'apple': {'UNIT': [2, 3]}},
    {'banana': {'UNIT': [5]}}
]

内容的提问来源于stack exchange,提问作者test new jiras

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:35:20