python - 在 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 的值作为列表索引?我一定遗漏了一些我看不到的非常明显和基本的东西吗?
解决方案
Input()
返回一个字符串。您将需要使用int()
转换为整数。
input()
资源
推荐阅读
- r - 如何使用 dplyr r 对 grouped_tbl 中的选择列使用行手段来改变新列?
- ios - 未执行 Segue
- java - 在安装了 facebook Lite 的手机上使用 facebook 按钮登录时出错
- typescript - 具有泛型的函数在其他函数中用作参数
- angular - 我可以跨 Nx Angular 单一存储库合并多个覆盖率报告吗?
- c# - Api 公开带有参数的 url
- python - 分组和重采样后如何索引数据?
- javascript - div 在项目页面上没有正确对齐
- django - djang oscar 优惠券和优惠
- c# - c# 从隐藏的输入中获取值