5.6.2 列表到字典的函数,针对好玩游戏物品清单

def addToInventory(inventory, addedItems):
...: # your code goes here
...: for i in range(len(addedItems)):
...: if addedItems[i] in inventory.keys():
...: inventory[str(addedItems[i])]+=1
...: else:
...: inventory[str(addedItems[i])]=1
...: return inventory

inv = {'gold coin': 42, 'rope': 1}
...: dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold c
...: oin', 'ruby']
...: inv = addToInventory(inv, dragonLoot)
...: displayInventory(inv)

======================网上一个更简洁的代码,=========================

def addToInventory(inventory,addedItems):
40 for item in addedItems:
41 inventory.setdefault(item,0)
42 inventory[item] += 1
43 return inventory

所有的知识点用到的方法还是要自己敲一敲,不然写的时候根本想不起来用啊。
只是知道有个东西。不能用上就不算学到。

0 条评论
发表一条评论