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

标签 python list integer slice

在我的代码中,我试图让用户输入以选择数组中的一个值,但是当有一个固定值(例如 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

谢谢

最佳答案

问题是 input 是一个 function 而不是 variable,因此你必须先调用它来分配输入的值到变量 x。更重要的是,错误非常具体 TypeError: list indices must be integers or slice, not builtin_function_or_method,这意味着变量 x 是一个函数,这是因为你赋值了在这种情况下,它是一个函数 input

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


highstreet[x]
print(highstreet[x])

关于python - 列表索引必须是整数或切片 python 3.6 list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43588178/

相关文章:

python - 如何使用 Sympy 解决不平等问题?

python - 按2列对np 2d数组进行排序(升序、降序)

list - Groovy:使用范围运算符创建列表

list - 如何将属性映射到 Ansible 中的列表字典中

javascript - 负数和正数的正则表达式

c++ - 条件中的二进制文字

python - 将元素/键分配给字典

Python:为什么 IDLE 这么慢?

python - 是否可以将此循环转换为 python 中的列表理解

python - 将整数转换为数字列表