TypeError:类型'NoneType'的对象没有len(),空变量?

问题描述 投票:0回答:1

我正在尝试编写一个递归函数,该函数将从提供的列表中返回最大值。我有一些代码正在尝试测试,并且抛出以下错误:

  line 10, in array_max
    if pos == len(num_list):
    TypeError: object of type 'NoneType' has no len()

我从一些探索中得知num_list = num_list.sort()返回None。我不知道为什么。下面是我当前的功能:

def array_max(num_list, pos = 0):
    num_list = num_list.sort()

    if pos == len(num_list):
        return num_list[pos]

    counting = array_max(num_list, pos+1)
    return counting

l1 = [5,6,3,44,1,-5]
test = array_max(l1)
print(test)

为澄清起见,我不是在寻找有关该功能其余部分的建议。我只是对为什么我得到这个错误感到困惑。谢谢。

python typeerror nonetype
1个回答
0
投票

list.sort()函数不返回新列表,实际上,不返回任何内容;因此,您稍后会遇到NoneType错误。相反,它将对列表的特定实例进行排序。

基本上是存储sort()函数的返回值(它是None),然后再尝试使用len(num_list)获得它的长度<=> len(None)

>>>a = [1, 4, 3, 2]
>>>a.sort()
>>>a
[1, 2, 3, 4]

但是sorted()函数返回一个新列表。

sorted()
© www.soinside.com 2019 - 2024. All rights reserved.