2016-01-05 22 views
0

我列出的兩個列表,長度相等,這樣之間串聯子表:Python的:不同的列表

lstA = [[1,4,5,6],[4,5],[5,6],[],[],[],[],[]] 
lstB = [[7,8],[4,5],[],[],[],[2,7,8],[7,8],[6,7]] 

而且我想在每個索引位置來串聯子表,以便他們做出一個子表,像這樣:

newlst = [[1,4,5,6,7,8],[4,5],[5,6],[],[],[2,7,8],[7,8],[6,7]] 

理想情況下,新的子列表將刪除重複項(如newlst [1])。我轉換的整數轉換爲字符串,並試圖這樣:

for i in range(len(lstA)): 
    c = [item + item for item in strA[i], strB[i]] 

但這增加的每個項目每個列表本身添加到其他列表前,導致這樣的事情:

failedlst = [[["1","4","5","6","1","4","5","6"],["7","8","7","8"]],[["4","5","4","5"],["4","5","4","5"]]...etc] 

這仍然沒有真正加入兩個子列表,只是創建了兩個子列表的新子列表。任何幫助將大大appeciated!

回答

5

通過並聯串聯物品製作清單是非常簡單的,與zip功能組合使用list comprehension

newlst = [x+y for x,y in zip(lstA, lstB)] 

如果要刪除重複項,可以使用set。如果您希望將這些項目重新排列在列表中,則可以使用sorted

在組合中,這樣:

newlst = [sorted(set(x+y)) for x,y in zip(lstA, lstB)] 
1

你可以使用:

lstA = [[1,4,5,6],[4,5],[5,6],[],[],[],[],[]] 
lstB = [[7,8],[4,5],[],[],[],[2,7,8],[7,8],[6,7]] 

answer = [] 
for idx in range(len(lstA)): 
    answer.append(sorted(list(set(lstA[idx]+lstB[idx])))) 

print(answer) 

輸出

[[1, 4, 5, 6, 7, 8], [4, 5], [5, 6], [], [], [2, 7, 8], [7, 8], [6, 7]] 
0

使用zipchain.from_iterableitertools模塊。

In [94]: from itertools import chain 

In [95]: lstA = [[1,4,5,6],[4,5],[5,6],[],[],[],[],[]] 

In [96]: lstB = [[7,8],[4,5],[],[],[],[2,7,8],[7,8],[6,7]] 

In [97]: [list(set(chain.from_iterable(item))) for item in zip(lstA, lstB)] 
Out[97]: [[1, 4, 5, 6, 7, 8], [4, 5], [5, 6], [], [], [8, 2, 7], [8, 7], [6, 7]] 

如果要排序,則子表:

In [98]: [sorted(set(chain.from_iterable(item))) for item in zip(lstA, lstB)] 
Out[98]: [[1, 4, 5, 6, 7, 8], [4, 4, 5, 5], [5, 6], [], [], [2, 7, 8], [7, 8], [6, 7]]