python - 属性错误 : 'NoneType' object has no attribute 'append' (recursion function)

标签 python list recursion append python-2.x

我正在尝试获得所有可能的骰子排列。下面是我的代码。

def PrintAllPerms(n, arr, str_):
    if (n == 0):
        print str_
        arr.append(str_)
        return arr
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]

PrintAllPerms(2,[],"")

但我只打印了这么多就出现了以下错误。

PrintAllPerms(2,[],"")

11
12
13
14
15
16
21

<ipython-input-7-d03e70079ce2> in PrintAllPerms(n, arr, str_)
      2     if (n == 0):
      3         print str_
----> 4         arr.append(str_)
      5         return arr
      6     else:

AttributeError: 'NoneType' object has no attribute 'append'

为什么它打印到 2,1 呢?

处理这个问题的正确方法是什么?

最佳答案

这是由于以下行:

arr = PrintAllPerms(n-1,arr,str_)

如果 else 路径,您的 PrintAllPerms 函数不会返回任何内容,因此被视为返回 None。所以 arr 被设置为 None

关于python - 属性错误 : 'NoneType' object has no attribute 'append' (recursion function),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44361237/

相关文章:

Python 导入在 travisCI 上失败但在本地失败

python - Request.get 突然开始遇到 "Temporary failure in name resolution"错误

c++ - 使用 Push、Pop 等在 C++ 中创建堆栈

c++ - 计算最大利润的代码

python - 递归:看起来像相同的函数,但打印出不同的执行流程

c++ - 树内容的格式化输出——先序遍历

python - 访问嵌套字典的数据

python - keras mnist.load_data() 速度超慢,一段时间后会抛出错误

无法创建结构列表

c# - 如何从列表中删除特定的游戏对象(在数组中)?