AttributeError: 'NoneType' object has no attribute 'append' (recursion function)

AttributeError: 'NoneType' object has no attribute 'append' (recursion function)

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

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_)

如果您的 PrintAllPerms 函数采用 else 路径,则它不会 return 任何东西,因此被视为 returning None .所以 arr 被设置为 None.

你需要在 else 分支中 return arr

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]
        return arr

PrintAllPerms(2)