我已经尝试过这个问题超过一个半小时了,我终于屈服了。尽可能地尝试,我无法将物品堆放在库存中。
详细地说,我随机生成了一个' drop'它有一个存储在数组中的名称和数量。 '下降'是一个2d数组,它包含这些子数组。我试图在一个玩家的库存中搜索这个数量,这个库存也有一个数量,当它添加到它时它会增加...如果它运行得很好。
import random as rd
inventory = []
items = ["gunk","gear","bolt","wheel","pinion"]
drops = []
while True:
enter = input("")
if enter == "":
drops = []
quantity = 1
drops.append([rd.choice(items),quantity])
print("drops",drops)
for i in range(len(drops)):
try:
add_to = inventory.index(drops[i])
inventory[add_to][1] += quantity
except:
inventory.append(drops[i])
print("inv",inventory)
输出(反复按回车键):
drops [['pinion', 1]]
inv [['pinion', 1]]
drops [['gunk', 1]]
inv [['pinion', 1], ['gunk', 1]]
drops [['pinion', 1]]
inv [['pinion', 2], ['gunk', 1]]
drops [['bolt', 1]]
inv [['pinion', 2], ['gunk', 1], ['bolt', 1]]
drops [['pinion', 1]]
inv [['pinion', 2], ['gunk', 1], ['bolt', 1], ['pinion', 1]]
正如您所看到的,由于数量与其搜索的数量不匹配,因此只需添加一个新数量。知道如何解决这个问题吗?
答案 0 :(得分:3)
此类事情的更好的数据类型是使用dict
作为库存,因为它可以跟踪给定键(项目)的数量:
import random as rd
inventory = {}
items = ["gunk","gear","bolt","wheel","pinion"]
drops = []
while True:
enter = input("")
if enter == "":
drops = []
quantity = 1
drops.append([rd.choice(items),quantity])
print("drops",drops)
for drop in drops:
item = drop[0]
qty = drop[1]
if item in inventory:
inventory[item] += qty
else:
inventory[item] = qty
print("inv", [[key, inventory[key]] for key in inventory])
以下是输出示例:
drops, [['gunk', 1]]
inv, [['gunk', 1]]
drops, [['wheel', 1]]
inv, [['wheel', 1], ['gunk', 1]]
drops, [['gunk', 1]]
inv, [['wheel', 1], ['gunk', 2]]
drops, [['gear', 1]]
inv, [['wheel', 1], ['gunk', 2], ['gear', 1]]
drops, [['pinion', 1]]
inv, [['wheel', 1], ['pinion', 1], ['gunk', 2], ['gear', 1]]
drops, [['gunk', 1]]
inv, [['wheel', 1], ['pinion', 1], ['gunk', 3], ['gear', 1]]
答案 1 :(得分:0)
您没有说明您正在使用哪个Python版本。根据您的print()
语法,我假设它是Python 3.x,对吧?
如果是这样,这可能是来自collections
模块的Counter
class的理想用例。 Counter
对象基本上是一个将整数作为值存储的字典。与@Alden建议的标准字典相比,优势在于您不必在第一次遇到密钥时初始化密钥:
import random as rd
import collections
# instead of a dict, use a Counter:
inventory = collections.Counter()
items = ["gunk","gear","bolt","wheel","pinion"]
drops = []
while True:
enter = input("")
if enter == "":
drops = []
quantity = 1
drops.append([rd.choice(items),quantity])
print("drops",drops)
for add_to, quantity in drops:
# if no value exists in 'inventory' for the key
# 'add_to', the value is assumed to be 0.
inventory[add_to] += quantity
print("inv", [[x, inventory[x]] for x in inventory])