列表索引必须是整数或切片python 3.6lis

2024-09-28 22:26:14 发布

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

在我的代码中,我试图让用户输入来选择数组中的一个值,但是当有一个固定的值(如2)时它仍然有效,但是当提到input()时它就不起作用了。

highstreet = ['tp' ,'io','fffffff','mmmmmm','ice']
x = input

highstreet[x]
print(highstreet[x])



 >> highstreet[x]
 >>TypeError: list indices must be integers or slices, not 
  builtin_function_or_method

谢谢


Tags: or代码用户ioinput数组listprint
2条回答

问题是inputfunction而不是variable,因此必须首先调用它,才能将输入的值赋给变量x。更重要的是,错误是非常具体的TypeError: list indices must be integers or slices, not builtin_function_or_method,这意味着变量x是一个函数,这是因为在本例中,您为它分配了一个function

x = int(input()) # int(raw_input()) in python 2


highstreet[x]
print(highstreet[x])

在Python3中,input()返回字符串值,而不是整数。因此,您需要将其转换为int。此外,要存储highstreet[x]的结果,请将其分配给一个变量并打印它:

x = int(input())
value = highstreet[x]
print(value)

相关问题 更多 >