python好玩游戏的物品清单_Python 好玩游戏的物品清单
stuff = {‘rope‘: 1, ‘torch‘: 6, ‘gold coin‘: 42, ‘dagger‘: 1, ‘arrow‘: 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + ‘ ‘ + k)
item_total += v
print("Total number of items: " + str(item_total))
displayInventory(stuff)
運行結果:
Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62
列表到字典的函數,針對好玩游戲物品清單
假設征服一條龍的戰利品表示為這樣的字符串列表:
dragonLoot = [‘gold coin‘, ‘dagger‘, ‘gold coin‘, ‘gold coin‘, ‘ruby‘]
寫一個名為 addToInventory(inventory, addedItems)的函數, 其中 inventory 參數
是一個字典, 表示玩家的物品清單(像前面項目一樣), addedItems 參數是一個列表,
就像 dragonLoot。
addToInventory()函數應該返回一個字典, 表示更新過的物品清單。請注意, 列
表可以包含多個同樣的項。你的代碼看起來可能像這樣:
def addToInventory(inventory, addedItems):
# your code goes here
inv = {‘gold coin‘: 42, ‘rope‘: 1}
dragonLoot = [‘gold coin‘, ‘dagger‘, ‘gold coin‘, ‘gold coin‘, ‘ruby‘]
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
新代碼:
stuff = {‘rope‘: 1, ‘torch‘: 6, ‘gold coin‘: 42, ‘dagger‘: 1, ‘arrow‘: 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + ‘ ‘ + k)
item_total += v
print("Total number of items: " + str(item_total))
#displayInventory(stuff)
def addToInventory(inventory, addedItems):
# your code goes here
for i in addedItems:
if i in inventory.keys():
inventory[i] += 1
else:
inventory.setdefault(i,1)
return inventory
inv = {‘gold coin‘: 42, ‘rope‘: 1}
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: 48
原文:https://blog.51cto.com/xxy12345/2425053
總結
以上是生活随笔為你收集整理的python好玩游戏的物品清单_Python 好玩游戏的物品清单的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 终于知道超级服务器和高质量服务器的区别了
 - 下一篇: B+树索引实战:全值匹配查询