在应该 return 字符串的函数中出现 NoneType 错误?

Getting NoneType Error in a function that is supposed to return a string?

我正在尝试从字符串列表中提取每个字符串的第一个字母。我知道我可以使用抽象列表函数来做到这一点,但我想使用结构递归来做到这一点。

考虑以下代码:

def acronym(los)
    if los != []:
        return los[0][0] + acronym(los[1:])

我收到以下错误:

builtins.TypeError: Can't convert 'NoneType' object to str implicitly

虽然我对 SOF 做了一些关于这个错误的研究,但我仍然不明白为什么这个函数应该 return None,当 los[0][0] 是一个字符串并且 acronym(los[1:]) 也是 return 一个字符串。

有什么建议吗?

每次 acronym() 调用自身时,它会调用列表中除第一个字符串以外的所有字符串:los[1:].

最终,当列表中只有一个字符串时,"all but the first string" 根本就不是字符串,因此在 next 调用中 acronym()los 是一个空列表,您的 if los != []: 测试失败。

因为在那种情况下你没有明确地 return 任何东西,所以 Python returns None 隐含地,它不能与你的字符串连接'已经建立:

>>> "Hhay" + None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'NoneType' object to str implicitly