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

Python 3.x中从数组向字典添加元素时出错,求技术解决方案

解决Python字典添加数组元素的Inventory函数问题

我看你在编写addToInventory函数时卡壳了,代码不仅没写完,还有拼写错误,我来帮你把这个问题理顺并修复好。

先看你代码里的问题

你写到ram[ite...这里就断了,明显是拼写错误(应该是itemindex),而且手动判断元素是否存在的逻辑可以更简洁,不用写冗余的if语句。

修正后的完整addToInventory函数

def addToInventory(inventory, addedItems):
    for item in addedItems:
        # 用get方法简化逻辑:存在则取当前值,不存在则默认0,然后加1
        inventory[item] = inventory.get(item, 0) + 1
    return inventory  # 返回更新后的字典,方便后续调用

怎么结合你的现有代码使用

把这个函数放到你的代码里,然后调用它更新库存:

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + " " + k)
        item_total += v
    print("Total number of items: " + str(item_total) + '\n')
displayInventory(stuff)

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = {'gold coin': 42, 'rope': 1}
# 调用函数更新库存
inv = addToInventory(inv, dragonLoot)
# 显示更新后的库存
displayInventory(inv)

运行效果说明

执行后你会看到更新后的库存输出:

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48

为什么这么写更合理

  • 用inventory.get(item, 0)代替手动判断:这个方法会自动处理“元素不存在”的情况,不存在时返回0,我们直接加1就能完成初始化;存在时就取当前计数加1,一行代码搞定原本需要两行的逻辑。
  • 返回更新后的字典:虽然字典是可变对象,函数内部修改会直接影响原字典,但返回的写法让代码可读性更强,调用者能清晰看到变量被更新了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 02:28:14