递归地将列表复制到python中的另一个列表 [英] recursively copy a list to another in python

查看:137
本文介绍了递归地将列表复制到python中的另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中将列表递归复制到另一个列表.为此,我已将字符串作为输入,定义了一个空列表,并将其作为列表发送给递归函数,以便我可以将该列表复制到另一个列表.但是,错误显示"NoneType"对象没有属性"append". 我想念什么?我已经将"S"定义为main()中的列表. 如果还有其他递归方法,则欢迎使用它们.

I want to copy a list to another recursively in python. For that purpose, i have taken string as input, defined an empty list and send them to recursive function as lists, so that i can copy the list to another list. However, the error displays "NoneType" object has no attribute "append". What am i missing ? i have defined "S" as list in main(). If there are other recursive methods, they are welcomed.

显示错误:

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()    `       

推荐答案

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

列表append()方法不返回更新的列表;它就地添加新项目并返回None.

The list append() method does not return the updated list; it adds the new item in-place and returns None.

因此,下一次对string_copy()的调用将以None作为s的值.

Therefore the next call to string_copy() will have None as the value for s.

这篇关于递归地将列表复制到python中的另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆