修正Python代码:英雄攻击土匪列表时保留字典其他键值对
问题:修正英雄攻击土匪的字典更新代码
我拥有两个字典列表:
bandits = [{'health': 15, 'damage': 2, 'id': 0}, {'health': 10, 'damage': 2, 'id': 0}, {'health': 12, 'damage': 2, 'id': 0}] hero = [{'name': "Arthur", 'health': 50, 'damage': 5, 'id': 0}]
想要模拟英雄对每个土匪发动攻击——把英雄的damage值从每个土匪的health值中扣除,最终土匪列表应变为:
bandits = [{'health': 10, 'damage': 2, 'id': 0}, {'health': 5, 'damage': 2, 'id': 0}, {'health': 7, 'damage': 2, 'id': 0}]
我尝试了以下代码:
for i, v in enumerate(bandits): bandits[i] = {k: (bandits[i][k] - hero[0].get('damage')) for k in bandits[i] if k=='health'}
运行后得到的结果是:
bandits = [{'health': 10}, {'health': 5}, {'health': 7}]
生命值计算正确,但土匪字典里的其他键值对都被删除了,请问该如何修正这段代码?
解决方法
方法1:直接修改原字典(最简洁高效)
不需要重新生成字典,直接遍历每个土匪字典,修改health字段即可,原字典的其他键值对会自动保留:
hero_damage = hero[0]['damage'] for bandit in bandits: bandit['health'] -= hero_damage
方法2:修正字典推导式
如果一定要用字典推导式,需要保留所有键,仅对health字段做减法操作,其他字段直接沿用原值:
hero_damage = hero[0].get('damage') for i, bandit in enumerate(bandits): bandits[i] = { k: (bandit[k] - hero_damage) if k == 'health' else bandit[k] for k in bandit }
方法3:复制字典后修改(保留原字典场景)
如果需要保留原始土匪字典不被修改,可以先复制原字典,再更新复制后的health值,最后替换回列表:
hero_damage = hero[0]['damage'] for i in range(len(bandits)): updated_bandit = bandits[i].copy() updated_bandit['health'] -= hero_damage bandits[i] = updated_bandit
内容的提问来源于stack exchange,提问作者aheuchamps
相关产品推荐
相关产品推荐

