我在游戏的一个地方遇到了麻烦,我将嵌套字典从一个移动到另一个。这是目前为止的代码
player_inventory_weapons = {
"0": {"Name ": "Basic sword", "Sharpness": 10, "Fire level": 0, "Poison": 0, "Resistance
addition": 5, "type": "weapons"}
}
player_equip_weapons = {
}
# move item from one dicionary to another
def equip():
inp = str(input("What item would you want to move over? ")) # input number that is the key of what you are trying to equip
if inp in player_inventory_weapons:
del player_equip_weapons #only one allowed at a time
player_equip_weapons[inp] = player_inventory_weapons[inp]
del player_inventory_weapons[inp]
equip()
当我尝试装备"基本剑"时;通过输入'0',它给了我错误'UnboundLocalError:本地变量'player_equip_weapons'在分配之前引用'我已经尝试了很多东西,但没有一个是有效的!如果你能帮忙的话,我将不胜感激。
不要删除变量,只需用clear()
方法清空字典。
def equip():
inp = input("What item would you want to move over? ") # input number that is the key of what you are trying to equip
if inp in player_inventory_weapons:
player_equip_weapons.clear() #only one allowed at a time
player_equip_weapons[inp] = player_inventory_weapons[inp]
del player_inventory_weapons[inp]
虽然我不确定为什么你会使用字典,如果它只能有一个项目在一个时间。
这是你的基本问题:
del player_equip_weapons # This line deletes the variable
player_equip_weapons[inp] = player_inventory_weapons[inp] # This line tries to access a variable that doesn't exist
因为你正在删除这个变量,你访问它的尝试将会失败。
请注意,您几乎不希望使用del
或全局变量。不如这样做:
def equip(inventory: dict):
inp = input("What item would you want to move over? ")
item = inventory.pop(inp, None)
if item is not None:
return {
"hand": inventory.get(inp, "Nothing")
}
else:
print("No such item in your inventory!")
return dict()
player_equipped_weapons = equip(player_inventory_weapons)
这将用你的装备函数的结果覆盖装备武器变量。通过这种方式,您不需要担心清除原始字典。而不是使用del
,你可以使用pop()
从你的库存数据中删除项目,这让你可以检查该项目是否确实存在。