Python:通过递归函数调用传递列表会导致列表变为"NoneType",为什么?

cas*_*dra 7 python recursion nonetype

我有以下递归函数:

def recurse(y,n):
    if len(y) == n:
        return y
    else:
        return recurse(y.append(1),n)
Run Code Online (Sandbox Code Playgroud)

当我运行它:

x=recurse([],10)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: object of type 'NoneType' has no len()
Run Code Online (Sandbox Code Playgroud)

似乎函数第一次超过if语句,然后进入下一级递归,那里,y.append(1)是'NoneType',为什么不是:'[1]'as预期?我已经考虑了一段时间,我似乎无法弄明白.任何见解都表示赞赏!

Ósc*_*pez 12

问题出在这里:

y.append(1)
Run Code Online (Sandbox Code Playgroud)

append()方法返回None,因此您无法传递其结果以构建输出列表(您必须先到append列表然后传递它,如其他答案所示).试试这个:

def recurse(y, n):
    if len(y) == n:
        return y
    else:
        return recurse(y + [1], n)
Run Code Online (Sandbox Code Playgroud)

上述解决方案更符合函数式编程风格.使用append向现有列表添加元素 - 这将改变函数参数,通常不是一个好主意.另一方面,y + [1]每次创建一个新列表,保持参数不变.功能编程的支持者会告诉你这是一件好事.


Tot*_*tem 5

list.append()在列表上调用append方法,当它修改列表时,它返回None.

所以它不会返回列表.

你想要的东西:

def recurse(y,n):
    if len(y) == n:
        return y
    else:
        y.append(1)
        return recurse(y,n) # explicitly pass the list itself
Run Code Online (Sandbox Code Playgroud)