首页 > 解决方案 > 在 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"

所以我尝试让equip_choice 成为一个整数,即使我只是尝试输入没有小数的数字并且仍然得到错误。我认为我并没有尝试使用字符串作为列表索引,但显然我错了。所以我试图强制equip_choice 变成这样的整数:

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)

但我仍然得到同样的错误。为什么我不能使用equip_choice 的值作为列表索引?我一定遗漏了一些我看不到的非常明显和基本的东西吗?

标签: pythonlistindexingpython-3.8

解决方案


Input()返回一个字符串。您将需要使用int()转换为整数。

input() 资源


推荐阅读