gpt4 book ai didi

python - 用 Python 自动化无聊的东西——第 5 章,奇幻游戏 list

转载 作者:行者123 更新时间:2023-11-28 22:08:05 26 4
gpt4 key购买 nike

下面是我测试的代码:

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

def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + str(k))
item_total += v
print('Total number of items: ' + str(item_total))

displayInventory(stuff)

##
inv = {'gold coin':42, 'rope':1}
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
def addToInventory(inventory, addedItems):
for i in addedItems:
inventory.setdefault(i, 0)
inventory[i] += 1
return inventory
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

我希望它回来

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

但我只得到 43 个“金币” key 。这是为什么?

最佳答案

问题是,您使用的是 set:

dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
print(dragonLoot)

输出:

{'dagger', 'gold coin', 'ruby'}

一套会确保每件元素都是独一无二的,因此重复的“金币”将被丢弃。

解决方案:改用列表:

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

输出:

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

关于python - 用 Python 自动化无聊的东西——第 5 章,奇幻游戏 list ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58928763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com