2017-01-01 72 views
0

我有2個清單的下面的形式:聯盟2列出的

list1 = [["abc",45,48],["def",13,16]] 
    list2 = [["efgh",67,71],["def",13,16]] 

我怎樣才能找到這些2所列出的工會嗎?

需要的輸出:

union_list = [["abc",45,48],["def",13,16],["efgh",67,71]] 

如果這可以幫助:正如你所看到的,list[0][1]list[0][2]integers,我們在必要時它強制轉換爲string

+0

[Pythonic方式創建多個列表中包含的所有值的聯合]的可能副本(http://stackoverflow.com/questions/2151517/pythonic-way-to-create-union-of-all-values-contained -in-multiple-lists) – Li357

回答

2

您可以使用set.union,也就是說,你可以兩個列表映射到元組的列表,然後將它們轉換成集,這樣就可以調用union方法:

u_set = set(map(tuple, list1)).union(map(tuple, list2)) 

# {('abc', 45, 48), ('def', 13, 16), ('efgh', 67, 71)} 

要將它們轉換回列表:

list(map(list, u_set)) 
# [['def', 13, 16], ['efgh', 67, 71], ['abc', 45, 48]] 
1

您可以使用集合理解。由於列表是不可排序的,所以必須使用tuple()

>>> list1 = [["abc",45,48],["def",13,16]] 
>>> list2 = [["efgh",67,71],["def",13,16]] 
>>> {tuple(sublist) for sublist in list1 + list2} 
set([('def', 13, 16), ('efgh', 67, 71), ('abc', 45, 48)]) 
>>> 
1

您可以使用

[list(x) for x in unique_everseen(tuple(y) for y in chain(list1, list2))] 

unique_everseen()可以在模塊itertools的文檔中找到。轉換爲元組是必要的,因爲列表類型不可哈希。

+0

在itertools庫中找到'chain()'。顯示您導入的功能通常是一個好主意,而不是僅僅使用它們。另外,每個功能的文檔鏈接都不會受到影響。 –

+0

@leaf我添加了itertools文檔的鏈接。請注意,unique_everseen不包含在itertools中,它被記錄爲(有用的)配方。 – Gribouillis