我正在尝试编写一个for循环,它将获取一个列表并将其值添加到字典中。例如,假设一个列表包含值:[书,硬币,书,书,计算机,包]。for循环将获取这些值并将其添加到字典中,其键是添加的项的名称,相应的值是项的数量。以下是我目前掌握的代码:
import pprint
def addToInventory(inventory, addedItems):
for i in addedItems:
inventory += addedItems.count(i)
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
pprint.pprint(str(v) + ' ' + k)
item_total += v
print("Total number of items: " + str(item_total))
stuff = {}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
# while True:
# item = raw_input('Please enter item name')
# if item == '':
# break
# quantity = input('and the number of this item?')
# stuff.setdefault(item, quantity)
# print stuff
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
addToInventory(stuff, dragonLoot)
displayInventory(stuff)
使用^{} :
输出
我想这就是你要找的。关键是只迭代新列表中的唯一项,并将其添加到现有字典中,或者在该项不存在时更新该项。在
同时,使用Stefan的方法。 如果库存是一个计数器,你可以这样做
^{pr2}$您可以使用
collection.Counter
:相关问题 更多 >
编程相关推荐