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

Python同键字典值相乘求和报错:TypeError及正确结果需求

问题分析与解决

错误原因

第12行的sum(menu_stock)触发报错,因为menu_stock是每次循环计算出的单个浮点数(比如第一个循环得到4.50*6=27.0),而sum()函数要求传入可迭代对象(比如列表、生成器),无法直接对单个数值执行求和操作。

同时原代码存在逻辑漏洞:每次循环都会覆盖total_stock_worth变量,即便sum能正常运行,最终也只会得到最后一个商品的库存价值,而非所有商品的总价值。

修正方案

方案1:累加变量逐步求和

初始化一个总和变量,每次循环将单个商品的库存价值累加到总和中:

# Create a list "menu" with 4 items
menu = ["sandwich", "burger", "fish", "chips"]
# Create a dictionary "stock" with the stock value for each item in the menu
stock = {"sandwich" : 6, "burger" : 5, "fish" : 6, "chips" : 10}
# Create a dictionary "price" with the price for each item in the menu
price = {"sandwich" : 4.50, "burger" : 6.00, "fish" : 6.50, "chips" : 3.50}

total_stock_worth = 0  # 初始化总和为0
for key in price:
    # 计算单个商品库存价值并累加到总和
    total_stock_worth += price[key] * stock[key]

# Print statement with the calculated total stock worth
print("The total stock worth is £" + str("{:.2f}".format(total_stock_worth)))

方案2:生成器表达式一次性求和

用更简洁的写法,直接生成所有商品的库存价值序列,再通过sum()一次性求和:

# Create a list "menu" with 4 items
menu = ["sandwich", "burger", "fish", "chips"]
# Create a dictionary "stock" with the stock value for each item in the menu
stock = {"sandwich" : 6, "burger" : 5, "fish" : 6, "chips" : 10}
# Create a dictionary "price" with the price for each item in the menu
price = {"sandwich" : 4.50, "burger" : 6.00, "fish" : 6.50, "chips" : 3.50}

# 遍历所有键,计算乘积后生成序列并求和
total_stock_worth = sum(price[key] * stock[key] for key in price)

# Print statement with the calculated total stock worth
print("The total stock worth is £" + str("{:.2f}".format(total_stock_worth)))

两种方案运行后都会输出目标结果:The total stock worth is £131.00


内容的提问来源于stack exchange,提问作者mandykg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:40:14