Python数学-TypeError:"NoneType"对象不可下标 [英] Python Math - TypeError: 'NoneType' object is not subscriptable

查看:364
本文介绍了Python数学-TypeError:"NoneType"对象不可下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个用于数学的小程序(没有特殊原因,只是出于某种原因),并且遇到错误"TypeError:'NoneType'对象不可下标.

I'm making a small program for math (no particular reason, just kind of wanted to) and I ran into the error "TypeError: 'NoneType' object is not subscriptable.

我以前从未见过此错误,所以我不知道这意味着什么.

I have never before seen this error, so I have no idea what it means.

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

推荐答案

lista = list.sort(lista)

应该是

lista.sort()

.sort()方法就位,并返回None.如果您希望某些东西不就地返回值,则可以使用

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

除了#1:请不要将您的列表称为list.可以破坏内置列表类型.

Aside #1: please don't call your lists list. That clobbers the builtin list type.

除了#2:我不确定这行的含义:

Aside #2: I'm not sure what this line is meant to do:

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.

? In other words, I don't know why you're calling str on things which are already str.

除了#3:有时您使用print("something")(Python 3语法),有时您使用print "something"(Python 2).后者会在py3中给您一个SyntaxError,因此您必须运行2. *,在这种情况下,您可能不想养成这个习惯,否则您将结束打印元组并加上额外的括号.我承认它在这里可以很好地工作,因为如果括号中只有一个元素,它不会被解释为元组,但是它对于python来说似乎很奇怪..

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..

这篇关于Python数学-TypeError:"NoneType"对象不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆