AttributeError:' NoneType'对象没有属性'追加' (递归函数)

时间:2017-06-05 03:22:16

标签: python list recursion append

我试图获得所有可能的骰子排列。以下是我的代码。

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之后呢?

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

2 个答案:

答案 0 :(得分:3)

这是由于以下一行:

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

如果PrintAllPerms函数采用else路径,则None函数不返回任何内容,因此被视为返回arr。因此None设置为$namePic = ""; foreach($_POST['ck'] as $ck){ $namePic.= $ck.", "; $namesPic = explode(",", $namePic); } $dompdf = new DOMPDF(); $html = ""; for($i = 0; $i < $count; $i ++){ $html.= "<html><head><style type='text/css'> </style></head><body><div style=\"page-break-after: always;\"><p align=\"center\"><img src=\"../folder/images/$namePic[$i]\" ></p></div>"; } $html.= "</body></html>"; $dompdf->load_html($html); $dompdf->set_paper("a4", "portrail"); $dompdf->render(); $pdf = $dompdf->output(); $folder = "../sample.pdf"; file_put_contents($folder,$pdf);

答案 1 :(得分:2)

您需要在else分支中返回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)