python 意外的属性错误

标签 python

我对 python 很陌生,作为练习,我编写了一个简单的反向函数。

代码:

def m_reverse(x):
     if len(x) == 1:
             return x
     return m_reverse(x[:-1]).insert(0,x[-1])

当我尝试时,我得到以下结果:

>>> m_reverse([1,2,3,4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in m_reverse
  File "<stdin>", line 4, in m_reverse
AttributeError: 'NoneType' object has no attribute 'insert'

我的错误是什么?我缺少任何关键数据吗?

最佳答案

对于 python 内置函数,如果函数就地改变参数,按照惯例它会返回 None。因此,由于 .insert 改变了列表,因此它返回 None

你的想法很好,我认为逻辑是有道理的——从实现的角度来看,你可以使用列表串联,而不是使用insert:

def m_reverse(lst):
    if len(lst) == 1:
       return lst
    else:
       return [lst[-1]] + m_reverse(lst[:-1])
       # return lst[-1:] + m_reverse(lst[:-1]) would also work.

关于python 意外的属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20250672/

相关文章:

python - 如何在 Django REST 框架中的 as_view 中传递额外的参数

python - 如何从 Python 中的字符串列表制作直方图?

python - 正则表达式不以相同的方式拆分文本

python - 将 mysql 连接到 django

python - 如何在 spark python 的一列中连接两个字符串列

python - 由于使用 PyArray_ENABLEFLAGS 导致 Jupyter 崩溃

Python PIL 粘贴

python - 如何将整数拆分为数字列表?

python - 匹配正则表达式或在找不到时保留空字符串

python - 如何在 Kivy + Python 上重新加载图像