Nat*_*ott 49 python sorting math in-place
我正在为数学创建一个小程序(没有特别的原因,只是想要)并且我遇到了错误"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)
Run Code Online (Sandbox Code Playgroud)
错误:
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
Run Code Online (Sandbox Code Playgroud)
DSM*_*DSM 46
lista = list.sort(lista)
Run Code Online (Sandbox Code Playgroud)
这应该是
lista.sort()
Run Code Online (Sandbox Code Playgroud)
该.sort()方法就位,并返回None.如果你想要一些非就地的东西,它会返回一个值,你可以使用
sorted_list = sorted(lista)
Run Code Online (Sandbox Code Playgroud)
除了#1:请不要打电话给你的名单list.这破坏了内置列表类型.
除了#2:我不确定这条线的意图:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
Run Code Online (Sandbox Code Playgroud)
这很简单
print "value 1a + value 2 = value 3a value 4"
Run Code Online (Sandbox Code Playgroud)
?换句话说,我不知道你为什么要调用str已经是str的东西.
除了#3:有时你使用print("something")(Python 3语法),有时你使用print "something"(Python 2).后者会在py3中给你一个SyntaxError,所以你必须运行2.*,在这种情况下你可能不想养成这个习惯,或者你会用额外的括号结束打印元组.我承认它在这里工作得很好,因为如果括号中只有一个元素,它不会被解释为元组,但它对于pythonic眼睛看起来很奇怪.
acu*_*ich 26
TypeError: 'NoneType' object is not subscriptable发生异常是因为实际值lista是None.TypeError如果您在Python命令行中尝试此操作,则可以重现您在代码中获得的内容:
None[0]
Run Code Online (Sandbox Code Playgroud)
其原因lista被设置为无,因为返回值list.sort()是None......它并没有返回原始列表的排序副本.相反,正如文档所指出的那样,列表就地排序而不是复制(这是出于效率原因).
如果您不想更改原始版本,可以使用
other_list = sorted(lista)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
257449 次 |
| 最近记录: |