在Python中使用用户输入索引列表

2024-06-17 11:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白用这种方法我做错了什么。它是从另一个类内方法调用的,例如:

def equip_menu(self): # this is not the actual method, but equip_choice is used only in the following lines
    #snipped code
    equip_choice = Input("Input the number of the item you want to equip:\n")
    self.select_from_list_equip(equip_choice) 

这是抛出错误的方法:

def select_from_list_equip(self, equip_choice): # Trying to select item in list self.backpack
    item_to_equip = self.backpack[equip_choice]
    print("*DEBUG* Equip chosen:", item_to_equip.name)
    playeritems.equip(item_to_equip)

我得到一个错误:

"classes.py", line 109, in select_from_list_equip
    item_to_equip = self.backpack[count]
TypeError: list indices must be integers or slices, not str"

所以我试着让Equipment\u选择一个整数,即使我只是试着输入不带小数的数字,仍然会得到错误。我认为我并没有试图使用字符串作为列表索引,但显然我错了。所以我试图强迫你的选择变成这样的整数:

def select_from_list_equip(self, equip_choice):
    int(equip_choice)
    item_to_equip = self.backpack[equip_choice]
    print("*DEBUG* Equip chosen:", item_to_equip.name)
    playeritems.equip(item_to_equip)

但我还是得到了同样的错误。为什么我不能使用选项的值作为列表索引?我一定是错过了一些非常明显和基本的我是盲目的


Tags: theto方法infromselfisdef