2013-11-09 10 views
0

我想追加兩人回到列表,以兩種不同的列表,如Python的追加兩回,兩份不同名單

def func(): 
    return [1, 2, 3], [4, 5, 6] 

list1.append(), list2.append() = func() 

任何想法?

+0

是否要追加列表'[1,2,3]'本身或物品? –

+1

不要把你的問題的答案。相反,通過點擊勾號接受一個。 – iCodez

+0

我想我沒關係與追加,因爲我將輸出這些到一個XML文件,我有我的功能在一個循環中運行,我想回是在單獨的行每次和每個列表中的每個值是在單獨的列。 – ThothsScribe

回答

3

您必須先獲取返回值,然後追加

res1, res2 = func() 
list1.append(res1) 
list2.append(res2) 

你似乎是在這裏返回列表,你確定你不是說要使用list.extend()呢?

如果您正在擴展list1list2,您可以用切片賦值:

list1[len(list1):], list2[len(list2):] = func() 

但是這是一個令人驚訝的),以新人和b)在我看來相當不可讀。我仍然使用單獨的任務,然後擴展調用:

res1, res2 = func() 
list1.extend(res1) 
list2.extend(res2) 
1

爲什麼不只是存儲返回值?

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) 

希望它有幫助!

0

一個行的解決方案是不可能的(除非你使用一些神祕的黑客,這始終是一個糟糕的主意)。

你能得到的最好的是:

>>> 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]] 
>>> 

它的可讀性和效率。