Skip to main content
 首页 » 编程设计

python之接收类型错误 : can only concatenate list (not "NoneType") to list

2025年04月02日9lori

在我的计算机科学课上,我们正在学习递归,但我很难理解它。我的任务之一是创建一个算法,该算法返回另一个与 L 相同的列表,除了 e 的所有元素都被删除。但是,我目前正在想出一个

TypeError: can only concatenate list (not "NoneType") to list

这是什么意思,我该如何解决

def removeAll(e, L): 
    '''returns another list that is identical to L except all elements of e are removed''' 
     if L==[]: 
         return [] 
     if L[0]!=e: 
         return [L[0]]+removeAll(e,L[1:]) 

Code

请您参考如下方法:

您正在检查 L 是否为空列表,并且您正在检查 L 的第一个元素是否不等于 e(因此是结果的一部分),但是一旦元素等于 e,您的函数将不返回任何内容,这意味着它返回默认值 None。使用 else 为该情况添加适当的处理:

else: 
    return removeAll(e, L[1:])