当我运行它时,金币的数量只增加了一个,尽管有三个额外的金币。我不知道我的逻辑有什么问题。我创建了两个函数:addToInventory,第一个参数是dictionary,第二个参数是list。如果字典中不存在键,则函数会将键添加到字典中,并将值递增1。displayInventory方法打印字典中的键/值。以下是我的源代码:
#fantasyGameInventory.py - a function that displays the inventory from a
#dictionary data structure
stuff = {'rope': 1, 'torch': 6, 'gold coin': 40, 'dagger': 1, 'arrow': 12}
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}
def addToInventory(inventory, addedItems):
#Iterate through the list
for k in addedItems:
#if key not in the dictionary, add to the dictionary and set its value to zero
inventory.setdefault(k,0)
inventory[k] = inventory[k] + 1
print(str(inventory[k]))
def displayInventory(inventory):
print('Inventory:')
itemTotal = 0
#iterate through the dictionary and print the key/values
for k, v in inventory.items():
print(k + ': ' + str(v))
itemTotal = itemTotal + v
print ('Total number of items: ' + str(itemTotal))
addToInventory(stuff, dragonLoot)
displayInventory(stuff)
它说有41枚金币,尽管显然应该有42枚:原来的40枚来自stuff
,加上另外两枚在dragonLoot
。你知道吗
首先需要将set更改为tuple,因为它在遍历列表时跳过重复的条目。你知道吗
以下是工作代码:
函数中的逻辑已经足够了,但是为“dragon\u loot”数据类型选择{set}是不合逻辑的;)
定义dragonLoot时,就是在定义一个
set
。集合是无序的,并且只有一个给定的项。在python中,大括号用于定义字典或集合—如果是键:值对,则是dict,否则是set。为了保持顺序和编号,我们可以使用元组(通常使用(foo,bar,coin,)形式定义)或列表(使用[foo,bar,coin]定义)。你知道吗相关问题 更多 >
编程相关推荐