您的位置:首页 > 编程语言 > Python开发

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

2018-01-26 09:51 741 查看
在一个打boss游戏,如何将掉落的物品添加到背包中:(教程第五章应用题)

def addToInventory(inventory , addedItems ):# 更新背包
c1={}
for add in addedItems:    #为boss物品创立字典
c1.setdefault(add,0)
c1[add]+=1
for k  in c1:     #为新增的种类创建进字典
if k not in inventory:  #种类不在inventory里,setdefault
c1.setdefault(k,0)

if k in inventory:   #种类在,加数量
c1[k]=c1[k]+inventory[k]
for k in inventory:     #谈论原来就有的情况
if k not in c1.keys():
c1.setdefault(k,0)
c1[k]+=1

return c1#这个用来最终更改好修改出来的字典c1

def displayInventory(inv):        #打印字典,即打印背包的物品
for k ,v in inv.items():
print(str(v) +' '+ k )

inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)
print('背包物品:')
displayInventory(inv)


输出如下:

背包物品:

45 gold coin

1 dagger

1 ruby

1 rope
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 新手