[英]Trouble with output for Fantasy Game Inventory
我是一名初学者,正在研究用 Python 自动化无聊的东西这本书。 我被困在这个练习问题上。 说明如下:
幻想游戏库存的字典功能列表:
想象一条被征服的龙的战利品表示为如下字符串列表:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
编写一个名为addToInventory(inventory, addedItems)
的函数,其中 inventory 参数是一个表示玩家库存的字典(就像在之前的项目中一样), addedItems
参数是一个类似于dragonLoot
的列表。 addToInventory()
函数应该返回一个表示更新后的库存的字典。 请注意, addedItems
列表可以包含多个相同的项目。 您的代码可能如下所示:
def addToInventory(inventory, addedItems):
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
上一个程序(使用上一个项目中的displayInventory()
函数)将输出以下内容:
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
我的代码如下
def addtoinventory(inventory,lootlist):
for i in range(len(lootlist)):
if lootlist[i] in inventory:
inventory[lootlist[i]] = inventory[lootlist[i]] + 1
else:
inventory.setdefault(lootlist[i],1)
return inventory
def displayinventory(inventory):
total_items = 0
for k,v in inventory.items():
print(k + ' : ' + str(v))
total_items = total_items + v
print("Total number of items: " + str(total_items))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addtoinventory(inv, dragonLoot)
displayinventory(inv)
我的输出是这样的:
gold coin : 45
ruby : 1
rope : 1
Total number of items: 47
我究竟做错了什么?
我认为您对else:
的缩进是错误的。 您应该使用 if-else,但您的代码是 for-else。 下面的代码运行良好。
def addtoinventory(inventory,lootlist):
for i in range(len(lootlist)):
if lootlist[i] in inventory:
inventory[lootlist[i]] = inventory[lootlist[i]] + 1
else:
inventory.setdefault(lootlist[i],1)
return inventory
结果如下。
>>> inv = {'gold coin': 42, 'rope': 1}
>>> dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
>>> inv = addtoinventory(inv, dragonLoot)
>>> inv
{'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}
我复制了您的代码,它对我来说工作得很好,除了项目及其编号的顺序错误,如果您将打印行更改为以下内容,这很容易解决:
print(str(v)+' : '+k)
这就是我解决它的方法。 不过,我无法摆脱括号,并且由于某种原因,pprint 无法正常工作。 但是这段代码无论如何都可以达到目的......
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
#Turn dragonLoot list in to a dictionary:
list={}
for i in dragonLoot:
if i not in list:
list.setdefault(i, 1)
elif i in list:
list[i] = list[i] +1
#Merge dictionaries:
for i, v in list.items():
if i not in inv:
inv.setdefault(i, 1)
elif i in inv:
inv[i]=inv[i]+v
import pprint
print('Inventory: ')
pprint.pprint(inv, width=1)
print('')
total=0
#Count the total number of items:
for i, v in inv.items():
total=total+v
print('Total number of items: ' + str(total))
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
item_total += v
print(str(v) + ' ' + str(k))
print("Total number of items: " + str(item_total))
def addToInventory(inventory, addItems):
for k in range(len(addItems)):
inventory.setdefault(addItems[k], 0)
inventory[addItems[k]] += 1
return(inventory)
inventory = {'rope': 1, 'torches': 6, 'gold coins': 42, 'daggers': 28, 'arrows': 12, 'knives': 50}
dragonLoot = ['gold coins', 'daggers', 'gold coins', 'gold coins', 'ruby']
updatedInventory = addToInventory(inventory, dragonLoot)
displayInventory(updatedInventory)
print("Inventory updated.")
尝试以下操作:
def addToInventory(dragonLoot,inv):
count={}
for item in dragonLoot:
count.setdefault(item,0)
count[item]=count[item]+1
for k in count.keys():
if k in inv.keys():
inv[k]=inv[k]+count[k]
print(inv)
您正在字典中搜索范围,并且您的代码存在意外缩进问题
playerInventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
for i in addedItems:
if i not in inventory:
inventory.setdefault (str(i), 1)
else:
inventory[i] = inventory[i] + 1
return inventory
playerInventory = addToInventory(playerInventory, dragonLoot)
print(playerInventory)
我刚刚进入这本书,在这里我如何解决它,看起来很简单:
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(backpack, added_items):
for i in added_items:
if i in backpack:
backpack[i] += 1
else:
count = 0
count += 1
backpack[i] = count
return backpack
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
for i in range(len(addedItems)):
if addedItems[i] in inventory:
inventory[addedItems[i]] = inventory[addedItems[i]] + 1
else:
inventory.setdefault(addedItems[i],1)
return inventory
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
这是我的解决方案:
# inventory.py
# 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))
def addToInventory(inventory, addedItems):
for i in addedItems:
#copy() is for to avoid RuntimeError: dictionary changed size during iteration
for k, v in inventory.copy().items():
if k == i:
inventory[k] = v + 1
if i not in inventory.keys():
inventory[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)
# displayInventory(stuff)
这就是我想出来的。 想分享,因为这是我在没有帮助的情况下做的第一个。 希望它有所帮助,欢迎所有反馈。
`
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = {'gold coin':42, 'rope': 1}
def addToInventory(inventory, addedItems):
for loot in addedItems:
inventory.setdefault(loot, 0)
for k, v in inventory.items():
if loot == k:
inventory[loot] = v + 1
def displayInventory(inventory):
totalItems = 0
for k, v in inventory.items():
print(str(v) + '---' + str(k))
totalItems += v
print('Total number of items: '+ str(totalItems))
addToInventory(inv, dragonLoot)
displayInventory(inv)
`
我就是这样做的。 我认为这是 addToInventory() 函数的一个干净的解决方案。 你怎么看? 还是我错过了什么?
PlayerInventory = {"gold coin": 42, "rope": 1}
dragonLoot = ["gold coin", "dagger", "gold coin", "gold coin", "ruby"]
def displayInventory(inventory): # Displays the Inventory
print("Inventory:")
cnt = 0
for k, v in inventory.items():
print(k + " : " + str(v))
cnt += v
print(f"Total number of items: {cnt}")
def addToInventory(inventory, addedItems): # Add items to the provided inventory
for item in addedItems: # Loops trough the provided list.
inventory.setdefault(item, 0) # Checks if the key exists. If not, adds it with a value of 0.
inventory[item] += 1 # Adds 1 to the value.
return inventory # returns the complete Dictionary
PlayerInventory = addToInventory(PlayerInventory, dragonLoot)
displayInventory(PlayerInventory)
def add(inventory,items):
for j in items:
for i ,k in inventory.copy().items():
if i==j:
inventory[i]=k+1
else:
inventory.setdefault(j,1)
print(inventory)
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
add(inv,dragonLoot)
我认为这将是最好的方法
from collections import Counter
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
dl = (dict(Counter(dragonLoot)))
def addToInventory(inventory, addedItems):
for key, v in addedItems.items():
if key not in inventory:
inventory.setdefault(key, 1)
elif key in inventory:
inventory[key] = inventory[key] + v
return inventory
addToInventory(inv,dl)
print(inv)
关于这个练习需要注意的重要一点是,它使用了上一个练习的功能,并且该练习的输出包含库存中的复数形式的项目,具体取决于项目的数量,所以这是我的两个练习的版本,遵循规则 我使用屈折模块将单词从 Here Is The Code 转换为复数:
import inflect #for plural forms of items in inventory
p = inflect.engine()
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory): #this is the previous exercise as we need this function to do this exercise
print("Inventory:")
item_total = 0
for k, v in inventory.items():
if v > 1: #'v' is huch of given item there is
key = p.plural(k) #if there is more than 1 of the given item 'k' converts it into plural form
else:
key = k #if there is only 1 of the item then no need for plural form
print('' + str(v) + ' ' + key ) #prints the number of items + the item name example: 12 torches or 1 ruby
item_total += v #v is added to item_total
print("Total number of items: " + str(item_total))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
for k in addedItems: #loops over the valus in the list addedItems which is dragonLoot in this case
if k in inventory.keys(): #if the current value of k is in the keys of inventory which is inv in this case the following code is executed this means that the dragons loot has the item 'k'
inventory[k] += 1 # 1 is added to the the key value of 'k' this means that the user got 1 more of the loot item
else:
inventory.setdefault(k, 1) # if k is not in the inventory then k is added to it and the value is set to 1
return inventory #then the edited inventory dict is returned
inv = addToInventory(inv, dragonLoot) # the function is called on inv and dragonLoot
displayInventory(inv) #the displayInventory fuction is called on inv dict
我希望这段代码能正常工作,因为我也是初学者“谢谢”
items={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(*inventory):
total_items = 0
for i, j in items.items():
print(j, i)
total_items += j
print("Total number of items: " + str(total_items))
displayInventory()
我将发布幻想游戏清单开头部分的解决方案以及幻想游戏清单的字典功能列表
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(invent):
print("Inventory: ")
total = 0
for x, y in inventory.items():
total = total + y
print(str(y) + " " + x)
print("A total of " + str(total) + " items")
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory,addedItems):
for x in addedItems:
inventory.setdefault(x, 0)
inventory[x] += 1
addToInventory(inventory, dragonLoot)
displayInventory(inventory)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.