Python将两个返回追加到两个不同的列表
我想将两个返回的列表附加到两个不同的列表中,例如Python将两个返回追加到两个不同的列表,python,return,append,Python,Return,Append,我想将两个返回的列表附加到两个不同的列表中,例如 def func(): return [1, 2, 3], [4, 5, 6] list1.append(), list2.append() = func() 有什么想法吗?您必须先捕获返回值,然后添加: res1, res2 = func() list1.append(res1) list2.append(res2) 您似乎正在返回列表,您确定不打算使用list.extend() 如果要扩展list1和list2,可以使用片分配:
def func():
return [1, 2, 3], [4, 5, 6]
list1.append(), list2.append() = func()
有什么想法吗?您必须先捕获返回值,然后添加:
res1, res2 = func()
list1.append(res1)
list2.append(res2)
您似乎正在返回列表,您确定不打算使用list.extend()
如果要扩展list1
和list2
,可以使用片分配:
list1[len(list1):], list2[len(list2):] = func()
但在我看来,这是a)让新来者感到惊讶的b)相当难以理解的。我仍然会使用单独的分配,然后扩展呼叫:
res1, res2 = func()
list1.extend(res1)
list2.extend(res2)
您必须首先捕获返回值,然后追加:
res1, res2 = func()
list1.append(res1)
list2.append(res2)
您似乎正在返回列表,您确定不打算使用list.extend()
如果要扩展list1
和list2
,可以使用片分配:
list1[len(list1):], list2[len(list2):] = func()
但在我看来,这是a)让新来者感到惊讶的b)相当难以理解的。我仍然会使用单独的分配,然后扩展呼叫:
res1, res2 = func()
list1.extend(res1)
list2.extend(res2)
为什么不存储返回值呢
a, b = func() #Here we store it in a and b
list1.append(a) #append the first result to a
list2.append(b) #append the second one to b
这样,如果a
以前是[10]
,而b
以前是[20]
,您将得到以下结果:
>>> a, b
[10, [1,2,3]], [20,[4,5,6]]
不,那不难,是吗
顺便说一下,您可能希望合并列表。为此,您可以使用extend
:
list1.extend(a)
希望有帮助 为什么不存储返回值呢
a, b = func() #Here we store it in a and b
list1.append(a) #append the first result to a
list2.append(b) #append the second one to b
这样,如果a
以前是[10]
,而b
以前是[20]
,您将得到以下结果:
>>> a, b
[10, [1,2,3]], [20,[4,5,6]]
不,那不难,是吗
顺便说一下,您可能希望合并列表。为此,您可以使用extend
:
list1.extend(a)
希望有帮助 一行解决方案是不可能的(除非你使用一些神秘的黑客,这总是一个坏主意) 您所能得到的最好结果是:
>>> list1 = []
>>> list2 = []
>>> def func():
... return [1, 2, 3], [4, 5, 6]
...
>>> a,b = func() # Get the return values
>>> list1.append(a) # Append the first
>>> list2.append(b) # Append the second
>>> list1
[[1, 2, 3]]
>>> list2
[[4, 5, 6]]
>>>
它可读性强,效率高。一行解决方案是不可能的(除非你使用一些神秘的黑客,这总是一个坏主意) 您所能得到的最好结果是:
>>> list1 = []
>>> list2 = []
>>> def func():
... return [1, 2, 3], [4, 5, 6]
...
>>> a,b = func() # Get the return values
>>> list1.append(a) # Append the first
>>> list2.append(b) # Append the second
>>> list1
[[1, 2, 3]]
>>> list2
[[4, 5, 6]]
>>>
它可读性强,效率高。您想将列表添加到
[1,2,3]
本身还是它的项目中?不要将答案放在您的问题中。相反,通过单击勾号来接受一个。我认为我可以追加,因为我将把它们输出到一个xml文件中,我的函数在循环中运行,我希望每次返回都在单独的一行上,每个列表中的每个值都在单独的列中。是否希望追加列表[1,2,3]
本身或其项目?不要在问题中给出答案。我想我可以追加,因为我将把它们输出到一个xml文件中,我的函数在一个循环中运行,我希望每次返回都在一个单独的行上,每个列表中的每个值都在单独的列中。