如何从字典列表中移除包含指定ID的字典元素?
解决思路与修正方案
你的代码目前存在一个核心问题:嵌套循环会让符合条件的字典被重复添加。比如id=20的游戏条目,会在遍历game_id_list的每一个元素时都被加入results,最终结果里会出现多次相同的字典,而且并没有真正过滤掉所有目标ID的项。
修正后的代码方案
方案1:使用列表推导式(最简洁高效)
列表推导式是Python处理这类过滤需求的常用方式,代码简洁且可读性拉满:
list_games = [ {'id': 10, 'name_game': 'x1'}, {'id': 20, 'name_game': 'x2'}, {'id': 30, 'name_game': 'x3'}, {'id': 40, 'name_game': 'x4'}, {'id': 50, 'name_game': 'x5'}, {'id': 60, 'name_game': 'x6'}, {'id': 70, 'name_game': 'x7'}, {'id': 80, 'name_game': 'x8'}, {'id': 90, 'name_game': 'x9'} ] game_id_list = [10, 30, 40] def remove_game_id_list(list_games, game_id_list): # 转成集合提升查找效率(如果排除列表很大的话效果更明显) exclude_ids = set(game_id_list) return [game for game in list_games if game['id'] not in exclude_ids] # 测试调用 print(remove_game_id_list(list_games, game_id_list))
方案2:修正你的原始循环写法
如果你更习惯传统循环的思路,只需要遍历一次游戏列表,逐个判断是否需要保留即可,完全不需要嵌套循环:
list_games = [ {'id': 10, 'name_game': 'x1'}, {'id': 20, 'name_game': 'x2'}, {'id': 30, 'name_game': 'x3'}, {'id': 40, 'name_game': 'x4'}, {'id': 50, 'name_game': 'x5'}, {'id': 60, 'name_game': 'x6'}, {'id': 70, 'name_game': 'x7'}, {'id': 80, 'name_game': 'x8'}, {'id': 90, 'name_game': 'x9'} ] game_id_list = [10, 30, 40] def remove_game_id_list(list_games, game_id_list): results = [] exclude_ids = set(game_id_list) for game in list_games: if game['id'] not in exclude_ids: results.append(game) return results # 测试调用 print(remove_game_id_list(list_games, game_id_list))
为什么要转成集合?
把game_id_list转成集合exclude_ids是因为集合的成员查找操作(in)时间复杂度是O(1),而列表的查找是O(n)。如果你的排除列表很长,用集合能显著提升代码运行效率;如果列表很短,直接用列表判断也没问题。
最终测试结果
运行上面的代码,会得到符合预期的过滤结果:
[{'id': 20, 'name_game': 'x2'}, {'id': 50, 'name_game': 'x5'}, {'id': 60, 'name_game': 'x6'}, {'id': 70, 'name_game': 'x7'}, {'id': 80, 'name_game': 'x8'}, {'id': 90, 'name_game': 'x9'}]
内容的提问来源于stack exchange,提问作者Drakhone
相关产品推荐
相关产品推荐

