2016-10-13 93 views
0

DISLCAIMER:我是新來的Python連接兩個二維列表成爲一個新的列表

我想通過合併現有2 2-d列出了在Python中創建一個級聯2-d列表。我開始用2所列出:

listA = [[a, b, c], [1, 2, 3]] 
listB = [[d, e, f], [4, 5, 6]] 

,我想做出一個新的列表(同時保留listA的和數組listB):

listC = [[a, b, c, d, e, f], [1, 2, 3, 4, 5, 6]] 

如果我嘗試將它們添加爲一維列表,我得到:

listA + listB 
result = [[a, b, c], [1, 2, 3], [d, e, f], [4, 5, 6]] 

我也曾嘗試:

listC = listA 
listC[0] += listB[0] 
listC[1] += listB[1] 

# This may be giving me the result I want, but it corrupts listA: 

Before: listA = [[a, b, c], [1, 2, 3] 
After: listA = [[a, b, c, d, e, f], [1, 2, 3, 4, 5, 6]] 

什麼是正確的方式來創建我想要的數據的新列表?

我也可以用一個元組工作:

listC = [(a, 1), (b, 2), (c, 3), (d, 4), (e, 5), (f, 6)] 

但不知道該方法無論是。

我目前使用Python 2.7(Raspberry Pi運行raspbian Jessie),但是如果需要的話可以使用Python 3.4。

回答

1

與列表理解創建一個新的列表,如

listC = [a+b for a,b in zip(listA, listB)] 
2

有幾種方法:

listC = [listA[0] + listB[0], listA[1] + listB[1]] 

listC = [x + y for x, y in zip(listA, listB)] 

很可能是兩種最簡單的

+0

謝謝!我其實只是在我自己的列表(listA)+ list(listB)中找到了我所需要的。 – thuper

1

這是一個功能性的方法,如果你想了解更多:

In [13]: from operator import add 
In [14]: from itertools import starmap 

In [15]: list(starmap(add, zip(listA, listB))) 
Out[15]: [['a', 'b', 'c', 'd', 'e', 'f'], [1, 2, 3, 4, 5, 6]] 

請注意,由於starmap如果您不想在列表中顯示結果(如果您只是想遍歷結果),因此starmap會返回迭代器,因此您不應在此處使用list()

+0

@downvoter如果我的答案有任何問題,我很樂意聽到這個消息。 – Kasramvd

+1

贊成'starmap' –