Python:TypeError:'NoneType' 对象没有属性 '__getitem__'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23322402/
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
Python: TypeError: 'NoneType' object has no attribute '__getitem__'
提问by user3578070
When I was trying to run this:
当我试图运行这个时:
lista=[4,10,4,15,6,15,18,10,7]
listb=[5,10,5,18,11,35,21,10,7]
import math
for i in range(9):
a=math.log10(lista[i])
b=math.log10(listb[i])
lista=lista.insert(i,a)
listb=listb.insert(i,b)
for i in range(17,8,-1):
lista.remove(lista[i])
listb.remove(listb[i])
print(lista)
print(listb)
Then I got :
然后我得到:
File "C:/Python27/Lib/site-packages/xy/untitled3.py", line 11, in <module>
a=math.log10(lista[i])
TypeError: 'NoneType' object has no attribute '__getitem__'
I need help. Thank you very much
我需要帮助。非常感谢
采纳答案by sshashank124
This is because insert()
doesn't return anythingand so you are assigning None
to your lists in the following lines:
这是因为insert()
不返回任何内容,因此您None
在以下几行中分配给您的列表:
lista=lista.insert(i,a)
listb=listb.insert(i,b)
Just doing the following is enough:
只需执行以下操作就足够了:
lista.insert(i,a)
listb.insert(i,b)
Examples
例子
a = [1,2,3]
b = a.insert(1,1)
>>> print b
None
>>> print a
[1,1,2,3]
回答by Martijn Pieters
lista.insert()
returns None
because the list is altered in-place, and does notreturn the updated list.
lista.insert()
返回None
因为列表改变就地,一点不返回更新列表。
During the second iteration of the loop then lista
is None
and lista[i]
fails.
在循环的第二次迭代,然后lista
是None
和lista[i]
失败。
Don't assign the result of the insertion:
不要分配插入的结果:
for i in range(9):
a=math.log10(lista[i])
b=math.log10(listb[i])
lista.insert(i,a)
listb.insert(i,b)
With that correction, your code prints:
通过该更正,您的代码将打印:
[0.6020599913279624, 0.6020599913279624, 0.6020599913279624, 0.6020599913279624, 0.6020599913279624, 0.6020599913279624, 0.6020599913279624, 0.6020599913279624, 0.6020599913279624]
[0.6989700043360189, 0.6989700043360189, 0.6989700043360189, 0.6989700043360189, 0.6989700043360189, 0.6989700043360189, 0.6989700043360189, 0.6989700043360189, 0.6989700043360189]