Python for循环满足指定条件时对两个字典值求和的问题求解
字典匹配取值求和问题修复方案
原有代码问题说明
- 循环逻辑完全错误:
planets.keys() and prices.keys()的运算结果是prices.keys(),循环只会遍历价格字典的键,而判断条件要求同一个键同时等于'Mars'和'First',该条件永远无法成立。 - 取值逻辑错误:
prices字典的值是整数类型,不是列表,不需要用[0]做索引取值。 - 存在缩进语法错误:原代码中
print(sum)行缩进位置不对,运行会直接报语法错误。 - 冗余逻辑:不需要遍历字典键,直接按键取值即可,执行效率更高。
依赖说明
该功能使用Python原生语法即可实现,不需要导入任何额外模块或第三方包。
正确实现代码
planets = { 'Mercury':['Estimated travel duration time: 6.5 years','./static/Hohmann_Mercury.gif', 110], 'Venus':['Estimated travel duration time: 15 months', './static/Hohmann_Venus.gif',90 ], 'Mars': ['Estimated travel duration time: 7 months','./static/Hohmann_Mars.gif', 160], 'Jupiter': ['Estimated travel duration time: 6 years','./static/Hohmann_Jupiter.gif',300], 'Saturn':['Estimated travel duration time: 7 years','./static/Hohmann_Saturn.gif',515], 'Uranus':['Estimated travel duration time: 8.5 years','./static/Hohmann_Uranus.gif',800], 'Neptune':['Estimated travel duration time: 12 years','./static/Hohmann_Neptune.gif',960]} prices = {'Economy':20, 'Business': 55, 'First': 70 } planet = 'Mars' price = "First" # 先判断传入的键在两个字典中都存在,避免键不存在抛出报错 if planet in planets and price in prices: total = planets[planet][2] + prices[price] print(total)
运行上述代码会输出预期结果230。
内容的提问来源于stack exchange,提问作者ed190
相关产品推荐
相关产品推荐

