inventory参数是表示玩家库存的字典,addedItems参数是列表。 addToInventory()函数应返回表示更新库存的字典。程序应输出以下内容:
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
这是我的代码:
def addToInventory(inventory, addedItems):
print('Inventory:')
totalItem = 0
for i in range(len(addedItems)):
if addedItems[i] in inventory:
inventory[str(addedItems[i])] += 1
if addedItems[i] not in inventory:
inventory[str(addedItems[i])] = 1
for k, v in inventory.items():
print(str(v) + ' ' + k)
totalItem += int(v)
print('Total number of items:' + str(totalItem))
inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)
我想知道如何处理for循环位。我现在觉得很奇怪(太长了)。 THX!
答案 0 :(得分:3)
你真的应该使用Counter
,这是内置词典的子类。
它对您的用例有三个优点:
Counter
个实例(即两个库存)非常容易。Counter
。Counter
将自动返回0. 演示:
>>> from collections import Counter
>>> inventory = Counter({'gold': 45,
... 'rope': 1,
... 'ruby': 1,
... 'dagger': 1}
... )
>>>
>>> def addToInventory(inventory, addedItems):
... inventory.update(addedItems)
...
>>> addToInventory(inventory, ['gold', 'gold', 'gold', 'dagger'])
>>> inventory
Counter({'gold': 48, 'dagger': 2, 'rope': 1, 'ruby': 1})
>>> addToInventory(inventory, {'ruby':100})
>>> inventory
Counter({'ruby': 101, 'gold': 48, 'dagger': 2, 'rope': 1})
>>> inventory['gold']
48
>>> inventory['flux capacitor']
0
答案 1 :(得分:0)
你可以看起来像这样:
for i in range(len(addedItems)):
inventory[i] = inventory.get(i, 0) + 1