代码之家  ›  专栏  ›  技术社区  ›  spider

在python中递归地将一个列表复制到另一个列表

  •  0
  • spider  · 技术社区  · 8 年前

    我错过了什么?我在main()中将“S”定义为list。

    显示错误:

    line 35, in string_copy
    return string_copy(k,s.append(k[i]),i+1)
    AttributeError: 'NoneType' object has no attribute 'append'
    

    def string_copy(k,s,i):
      if (i == len(k)):
        return s;
      else:
        return string_copy(k,s.append(k[i]),i+1)
    
    
    def main():
      print("enter the string you want to copy:");
      k = input();
      s = [None];
      i = 0;
      print("the type of k and s is:", type(k),type(s));
      res = string_copy(list(k),list(s),i);
      print("the desired results are:","\n", res);
    if __name__ == "__main__": main()    `       
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   John Gordon    8 年前

    return string_copy(k,s.append(k[i]),i+1)

    名单 append() 方法不返回更新的列表;它将新项添加到位并返回 None .

    所以下一个电话 string_copy() s .

        2
  •  0
  •   spider    8 年前

    最终解决方案是:

    def string_copy(k,s,i):
      if (i == len(k)):
        return s
      else:
        s.append(k[i])
        return string_copy(k,s,i+1)
    
    def main():
       print("enter the string you want to copy:")
       k = input()
       s = ""
       i = 0;
       print("the type of k is:", type(k))
       res = string_copy(list(k),list(s),i)
       print("the desired results are:","\n", "".join(res))
    if __name__ == "__main__": main()        
    

    def string_copy(k):
      if (len(k) == 0):
        return k
      else:
        return k[0] + string_copy(k[1:])
    
    def main():
      print("enter the string you want to copy:")
      k = input()
      print("the type of k is:", type(k))
      res = string_copy(k)
      print("the copied string is:","\n",res)
    if __name__ == "__main__": main()