【问题标题】:List indices must be integers or slices python 3.6 list列表索引必须是整数或切片 python 3.6 list
【发布时间】:2017-09-21 03:21:56
【问题描述】:

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

谢谢

【问题讨论】:

  • x = input 将函数input 分配给变量x。如果你想调用输入函数,并将结果赋值给x,你的意思是x = input()

标签: python list integer slice


【解决方案1】:

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

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


highstreet[x]
print(highstreet[x])

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2020-11-21
      • 2017-10-08
      • 2019-12-04
      相关资源
      最近更新 更多