You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 15:42:08