Python如何将游戏名称插入字典对应值列表的索引0位置?
问题需求说明
现有两个原始数据结构:
all_list = [['G05', 'Hopscotch', 'N', '2'], ['G07', 'Dominoes', 'S', '5'], ['G08', 'Chess', 'N', '3'], ['G10', 'Monopoly', 'N', '3'], ['G02', 'MineCraft', 'S', '5']] game_match = {'G02': [5, 3, 2, 0, 0], 'G05': [5, 3, 2, 0, 0], 'G07': [5, 2, 3, 0, 2], 'G08': [5, 2, 3, 1, 2], 'G10': [5, 1, 4, 2, 2]}
- 匹配规则:匹配
all_list和game_match中相同的game_id(即GXX字段),将all_list对应记录索引1位置的游戏名称,插入到game_match对应值列表的索引0位置。
错误原因
你的代码中使用的append()方法作用是将元素追加到列表末尾,因此游戏名称出现在了列表最后,不符合插入到开头的需求。
修复方案
方案1:使用列表insert()方法直接修改
list.insert(索引, 元素)可以将元素插入到列表指定位置,插入到开头索引填0即可:
for k, v in game_match.items(): for data in all_list: if k == data[0]: game_match[k].insert(0, data[1]) print(game_match)
方案2:优化写法(性能更高)
提前把all_list转成ID和名称的映射字典,避免双层循环,数据量大的时候效率提升更明显:
# 先构建game_id到游戏名称的映射字典 id_to_name = {item[0]: item[1] for item in all_list} for k in game_match: if k in id_to_name: # 列表拼接实现将名称放在开头 game_match[k] = [id_to_name[k]] + game_match[k] print(game_match)
最终输出
两种方案都可以得到预期结果:
{'G02': ['MineCraft',5, 3, 2, 0, 0], 'G05': ['Hopscotch', 5, 3, 2, 0, 0], 'G07': ['Dominoes', 5, 2, 3, 0, 2], 'G08': [ 'Chess', 5, 2, 3, 1, 2], 'G10': ['Monopoly', 5, 1, 4, 2, 2]}
内容的提问来源于stack exchange,提问作者Miracle
相关产品推荐
相关产品推荐

