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]}}]
问题根源
- 每次匹配到对应类型时,代码会遍历整个
types列表收集所有id,而非仅当前类型的id - 每匹配到一个
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
相关产品推荐
相关产品推荐

