我正在为数学制作一个小程序(没有特别的原因,只是想要)并且我遇到了错误“TypeError:'NoneType'对象不可订阅。
我以前从未见过这个错误,所以我不知道这意味着什么。
import math
print("The format you should consider:")
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
print("Do not include the letters in the input, it automatically adds them")
v1 = input("Value 1: ")
v2 = input("Value 2: ")
v3 = input("Value 3: ")
v4 = input("Value 4: ")
lista = [v1, v3]
lista = list.sort(lista)
a = lista[1] - lista[0]
list = [v2, v4]
list = list.sort(list)
b = list[1] = list[0]
print str(a)+str("a")+str(" = ")+str(b)
错误:
Traceback (most recent call last):
File "C:/Users/Nathan/Documents/Python/New thing", line 16, in <module>
a = lista[1] - lista[0]
TypeError: 'NoneType' object is not subscriptable
答案 0 :(得分:37)
lista = list.sort(lista)
这应该是
lista.sort()
.sort()
方法就位,并返回None。如果你想要一些非就地的东西,它返回一个值,你可以使用
sorted_list = sorted(lista)
除了#1:请不要拨打您的列表list
。这破坏了内置列表类型。
除了#2:我不确定这条线的意图:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
只是
print "value 1a + value 2 = value 3a value 4"
?换句话说,我不知道你为什么要调用已经str的东西。
除了#3:有时你使用print("something")
(Python 3语法),有时你使用print "something"
(Python 2)。后者会在py3中给你一个SyntaxError,所以你必须运行2. *,在这种情况下你可能不想养成这个习惯,或者你会用额外的括号结束打印元组。我承认它在这里工作得很好,因为如果括号中只有一个元素,它不会被解释为元组,但它对于pythonic眼睛看起来很奇怪..
答案 1 :(得分:23)
发生例外TypeError: 'NoneType' object is not subscriptable
,因为lista
的值实际上是None
。如果您在Python命令行中尝试此操作,则可以重现代码中的TypeError
:
None[0]
lista
设置为无的原因是因为list.sort()
的返回值为None
...它不会返回已排序的副本原始清单。相反,作为documentation points out,列表会按就地排序,而不是正在制作副本(这是出于效率原因)。
如果您不想更改原始版本,可以使用
other_list = sorted(lista)
答案 2 :(得分:0)
在此链接https://docs.python.org/2/tutorial/datastructures.html,您可以阅读此方法 &#34;对列表中的项目进行排序&#34;这意味着结果值将在排序和 结果将是自己的。该函数返回None。
将结果分配给&#34; lista&#34;在第14行
lista = list.sort(lista)
您所在区域将其设置为无。那是错误。没有人总是没有数据也不可能 标化。 &#34; TypeError:&#39; NoneType&#39;对象不是可订阅的&#34;
更正此错误(对列表进行排序)请在第14行执行此操作:
lista.sort() # this will sort the list in line
但还有一些其他错误: 在第18行中,当你指定:
list = [v2, v4]
你破坏了这个内置类型&#34; list&#34;并且您将收到以下错误:
TypeError: 'list' object is not callable
要纠正这一点,请说:
lista2 = [v2, v4]
第19行再次出现第14行的相同错误。这样做可以对另一个列表进行排序:
lista2.sort()
在第21行中,您尝试索引内置类型列表。要纠正这样做:
b = lista2[1] = lista2[0]
有了这个,你的代码就可以运行了。最后整个正确的代码:
import math
print("The format you should consider:")
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
print("Do not include the letters in the input, it automatically adds them")
v1 = input("Value 1: ")
v2 = input("Value 2: ")
v3 = input("Value 3: ")
v4 = input("Value 4: ")
lista = [v1, v3]
lista.sort()
a = lista[1] - lista[0]
lista2 = [v2, v4]
lista2.sort()
b = lista2[1] = lista2[0]
print str(a)+str("a")+str(" = ")+str(b)
答案 3 :(得分:0)
如先前在答案之一中所述,当列表的值原来为空时,会发生此错误。很好,尽管与该问题并不完全相关,但是在使用opencv和numpy读取图像时,对我来说发生了相同的错误,因为发现文件名可能与指定的文件名不同,或者由于未正确指定工作目录。