Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对于Python,是否有更好的方法将参数附加到列表中?_Python_List_Append - Fatal编程技术网

对于Python,是否有更好的方法将参数附加到列表中?

对于Python,是否有更好的方法将参数附加到列表中?,python,list,append,Python,List,Append,编写一个名为append_three_elements的函数。此函数接受四个参数作为参数。首先是我们将要添加到的列表,接下来的三个是要添加到列表中的值。此函数应返回一个新列表,并在列表末尾按顺序附加三个值 比如说,, 附加三个元素([],1,2,3) 你会期望回来的 [1,2,3] def append_three_elements(lst, a, b, c): lst1 = lst.copy() lst1.append(a) lst1.append(b) ls

编写一个名为append_three_elements的函数。此函数接受四个参数作为参数。首先是我们将要添加到的列表,接下来的三个是要添加到列表中的值。此函数应返回一个新列表,并在列表末尾按顺序附加三个值

比如说,, 附加三个元素([],1,2,3)

你会期望回来的 [1,2,3]

def append_three_elements(lst, a, b, c):
    lst1 = lst.copy()

    lst1.append(a)
    lst1.append(b)
    lst1.append(c)

    return lst1

这是一个没有终点的递归函数。它将不停地转来转去。 请尝试以下方法:

def附加三个元素(a、b、c、lst):
new_lst=lst.copy()
对于(a,b,c)中的i:
新增附加(一)
返回新的\u lst

这将获取列表的副本(如果您仅使用
new_lst=lst
,它仍将引用同一对象),然后在返回新列表之前追加三个不同的值(它不会修改原始列表)。

一个有趣且简短的解决方案。然而,Mark的解决方案更专业,可能是您正在寻找的正确答案

def附加三个元素(lst,*args):
返回lst+列表(args)
lst=附加三个元素(['lol'],1,2,3)
打印(lst)#>>['lol',1,2,3]

您能分享一个更好的代码/函数来运行这个问题吗?在python中,您可以只返回lst+[a,b,c],但是您应该仔细检查说明-列表在参数中排在第一位:
附加三个元素([],1,2,3)
谢谢标记!我忘了that@KateKiatsiri另一种只是为了好玩的方式是
return[*lst,a,b,c]
Ah!谢谢@胡安帕·阿里维拉加:)顺便说一句,马克·迈耶确实有一种非常简洁的方法来做同样的事情。如果您愿意放弃您的格式,请优先使用his。谢谢!我两个都喜欢!:)