Python 这段代码的错误“int object has no attribute __getitem__”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21355011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:39:05  来源:igfitidea点击:

What does the error "int object has no attribute __getitem__" mean for this code?

pythonpython-2.7numpy

提问by user3235485

I want a loop to create an array of 11 integers y[i]such that y[i] = (i+1)*(i+2)and it gives me an error which I don't understand.

我想要一个循环来创建一个包含 11 个整数的数组,y[i]这样y[i] = (i+1)*(i+2)它就会给我一个我不明白的错误。

In [100]: y = zeros(11)
     ...: for i in range(11):
     ...:     y[i] = (x[i]+1)*(x[i]+2)
     ...:     
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-100-7a762b788eff> in <module>()
      1 y = zeros(11)
      2 for i in range(11):
----> 3     y[i] = (x[i]+1)*(x[i]+2)
      4 

TypeError: 'int' object has no attribute '__getitem__' 

采纳答案by Martijn Pieters

xis an integer, notan array:

x是一个整数,而不是一个数组:

>>> x = i = 0
>>> x[i]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__' 

You need to scan back in your code and see what rebound xto an integer.

你需要扫描你的代码,看看什么反弹x到一个整数。

Your questionhowever implies you think you are executing:

但是,您的问题意味着您认为您正在执行:

y[i] = (i+1)*(i+2)

but your actual code sample clearly shows you are not. Figure out which code should actually run here first.

但您的实际代码示例清楚地表明您不是。弄清楚哪些代码应该首先在这里运行。

回答by embert

Basically that means, that you try to do []on an intso yor xin your code is an integer

基本上这意味着,您尝试[]intsoyx在您的代码中做的是integer