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

查看:31
本文介绍了Python Math - 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("
")

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("
")

是不是很简单

print "value 1a + value 2 = value 3a value 4"

?换句话说,我不知道你为什么要在已经是 str 的东西上调用 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.*,在这种情况下你可能不想养成这个习惯,否则你会打印出带有额外括号的元组.我承认它在这里工作得很好,因为如果括号中只有一个元素,它不会被解释为元组,但它在 Pythonic 眼中看起来很奇怪..

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 Math - TypeError:“NoneType"对象不可下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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