我是一名初学者,致力于使用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
我做错了什么?
答案 0 :(得分:1)
我认为你的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}
答案 1 :(得分:1)
我复制了您的代码,对我来说很好用,除了项目及其编号的顺序错误之外,如果将打印行更改为此,则很容易解决:
print(str(v)+' : '+k)
答案 2 :(得分:0)
这就是我解决的方法。但是我无法摆脱括号,由于某种原因,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))
答案 3 :(得分:0)
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.")
答案 4 :(得分:0)
尝试以下操作:
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)
答案 5 :(得分:0)
您正在字典中搜索范围,并且代码中出现意外缩进的问题
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)
答案 6 :(得分:0)
我刚进入书中,在这里我如何解决它,看起来很简单:
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
答案 7 :(得分:0)
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)
答案 8 :(得分:0)
这是我的解决方案:
# 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)
答案 9 :(得分:0)
我就是这么想的。想分享,因为这是我在没有帮助的情况下做的第一个。希望它有所帮助,欢迎所有反馈。
`
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)
`
答案 10 :(得分:0)
我就是这样做的。我认为这是 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)
答案 11 :(得分:0)
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)
我认为这是最好的方法
答案 12 :(得分:-1)
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()