将列表中的项目添加到Python中的字典中
我正在做这里找到的第二个练习。 https://automatetheboringstuff.com/chapter5(“List to Dictionary Function for Fantasy Game Inventory”)将列表中的项目添加到Python中的字典中
任务是将列表中的项目添加到字典中。
由于一些奇怪的原因,我的for循环没有遍历整个列表。你能帮我理解为什么吗?
def addToInventory(inventory, addedItems):
for i in addedItems:
if i in inventory:
inventory[i] = inventory[i] + 1
else:
inventory[i] = 1
return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
print(inv)
当运行该代码时,结果是“{‘绳’:1‘金币’:43}” 所以金币键的值被增加1(不是由3,其它应该),而'匕首'和'红宝石'被忽略。
我在其他地方找到了一个可行的解决方案,但我真的很想理解为什么这段代码不起作用。
在此先感谢。
def addToInventory(inventory, addedItems):
for i in addedItems:
if i in inventory:
inventory[i] = inventory[i] + 1
else:
inventory[i] = 1
return inventory
(return
for
后,不经过if
。)
我不知道为什么这得到了投票;这是正确的答案! –
您已经提供了代码并显示了您已更改的内容,但未解释原因。 (注意:我不是downvoter) – byxor
此外这只是一个错字。 OP应该知道如何正确缩进代码。 –
的问题是一个简单的压痕错字。现在,如果我们试图编写一些更高效的/ pythonic代码,我们可以使用collections.Counter
这是一种计算项目的专用字典类型。您的代码可以缩短和优化:
from collections import Counter
inv = Counter({'gold coin': 42, 'rope': 1})
inv.update(['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'])
print(inv)
结果:
Counter({'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1})
感谢downvoting试图改进python编码的答案。 –
并感谢纠正upvote :) –
谢谢,感谢。 –
'回报inventory'是你'for'循环中!它立即返回 –