【问题标题】:AttributeError: 'NoneType' object has no attribute 'append' (recursion function)AttributeError:“NoneType”对象没有“附加”属性(递归函数)
【发布时间】:2017-11-05 18:31:57
【问题描述】:

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

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

什么是正确的处理方式?

【问题讨论】:

    标签: python list recursion append python-2.x


    【解决方案1】:

    这是由于以下行:

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

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

    【讨论】:

      【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 2019-01-01
        • 2021-12-26
        • 2019-07-23
        • 2018-05-13
        • 2020-09-07
        相关资源
        最近更新 更多