Notes learning python "python programming quick start - let automate the tedious work of" Four

Problem four:
You create a fun video game. For data structure modeling on the players list item is a dictionary. Where the key is a string, describing the list of items, the value is an integer value, indicating how many players the article. For example, dictionary values { 'rope': 1, ' torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means that the player has a rope, six torches, 42 gold and so on.

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
dragdic={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def addtobag(inventory,additems):
	print('物品清单如下:')
	for i in additems:
		num=additems.count(i)#计算列表中物品出现次数
		l_num=inventory.get(i,0)#获得字典中已有物品
		#根据列表中的物品改变字典中的值
		inventory[i]=l_num+num
		#根据字典中值的大小进行排序打印
	for i,k in sorted(inventory.items(),key=lambda x : x[1]):
		print(k,i)
		#用sum()方法计算字典中物品总数
	print('物品总数为:',sum(inventory.values()))
****###考虑更简单的算法****
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
dragdic={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
#更简单的方法
for i in dragonLoot:
	# print(dragdic.get(i,0))
	# print('------------------')
	dragdic[i]= dragdic.get(i,0)+1#每次重新给键赋值,遇到相同则加1,遇到没有的键值则添加。
print(dragdic)
本来想用字典推导来做,但是命名空间问题实现不了重新给键赋值。
Published 23 original articles · won praise 5 · Views 390

Guess you like

Origin blog.csdn.net/weixin_43287121/article/details/104479133