dict中的值不会让我改变我

2024-04-24 03:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个程序来更新字典中的值。你知道吗

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

#stuff = addToInventory(stuff, dragonLoot)
for i in range(len(dragonLoot)):
        for k, v in stuff.items():
            if dragonLoot[i] == k:
                v += 1

displayInventory(stuff)

如您所见,我已经移动了main中的代码段,以确保它不是函数的问题。外部for循环也可以工作。问题是,v无法更新。displayInventory()打印与顶部声明中相同的值。你知道吗

提前感谢您的投入!你知道吗


Tags: in程序for字典torchcoinrubyrope
3条回答

Python中的+=操作符很棘手。对于某些类型,它将在原地修改左侧引用的对象。但是在其他情况下,这是不可能的(因为类型是不可变的)。在这些情况下,它会将左侧重新绑定到新对象。这不会更改其他地方可能存在的对旧值的引用。你知道吗

您可以在一个更简单的场景中了解这一点:

x = 1
y = x    # reference to the same int object
y += 1   # can't modify 1 in place, so only rebinds
print(x) # prints 1 still

在代码中,xstuff[k](通过循环隐式访问),而yv。您需要编写stuff[k] = v+1,以使您的代码实现所需的功能。你知道吗

v确实得到了更新,但是stuff[k]没有得到更新-它们是相同的值(最初),但不是相同的变量。您需要将新值赋给stuff[k],而不是v。你知道吗

您可以使用以下方法:

stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

for item in dragonLoot:     
    stuff[item] = stuff.get(item, 0) + 1

print stuff

给你:

{'gold coin': 45, 'dagger': 2, 'torch': 6, 'rope': 1, 'arrow': 12, 'ruby': 1}

stuff.get(item, 0)从字典返回item,但如果它不存在(例如ruby),则返回默认值0。我把它赋给字典,然后把它加回去。你知道吗

相关问题 更多 >