Python Math-TypeError:“NoneType”对象不是subscriptab

2024-04-26 21:58:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个数学小程序(没有特别的原因,只是有点想),我遇到了一个错误“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

Tags: theininputvalue错误notlistv2
3条回答
lista = list.sort(lista)

这应该是

lista.sort()

方法.sort()已就位,但未返回任何值。如果您希望某个不在适当位置的对象返回一个值,可以使用

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的东西调用str

旁白3:有时使用print("something")(Python 3语法),有时使用print "something"(Python 2)。后者将在py3中给您一个SyntaxError,因此您必须运行2.*,在这种情况下,您可能不想养成这个习惯,否则您将打印带有额外括号的元组。我承认它在这里工作得很好,因为如果括号中只有一个元素,它就不会被解释为元组,但是在Python眼里它看起来很奇怪。。

在这个链接https://docs.python.org/2/tutorial/datastructures.html你可以阅读这个方法 “对列表中的项目进行就地排序”这意味着结果值将在 结果将由自己决定。函数不返回任何值。

当你把结果赋给第14行的“lista”时

lista = list.sort(lista)

区域设置为“无”。这就是错误。没有总是没有数据,不能 可订阅。”TypeError:“NoneType”对象不可订阅

要更正此错误(对列表排序),请在第14行执行以下操作:

lista.sort() # this will sort the list in line

但还有其他一些错误: 在第18行中指定:

list = [v2, v4]

关闭此内置类型“list”,将得到以下错误:

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)

异常TypeError: 'NoneType' object is not subscriptable发生是因为lista的值实际上是None。如果在Python命令行中尝试此操作,则可以重新生成代码中的TypeError

None[0]

之所以将lista设置为None,是因为list.sort()的返回值是None。。。它不会返回原始列表的排序副本。相反,作为documentation points out,列表将在适当的位置进行排序,而不是进行复制(这是为了提高效率)。

如果不想更改原始版本,可以使用

other_list = sorted(lista)

相关问题 更多 >