2013-02-27 124 views
2

如果list1中的元素存在或列表2中存在公共元素,我想從list1的元組中創建一個新的元組列表。在Python中從兩個元組列表中選擇元組,如果兩個列表都包含公共元素

list1 = [('We', 'all'), ('all', 'live'), ('live', 'in'), ('in', 'a'), 
     ('a', 'yellow'), ('yellow', 'submarine.')] 

list2 = [('A', 'live'), ('live', 'yellow'), ('yellow', 'submarine'), 
     ('submarine', 'lifeform'), ('lifeform', 'in'), ('in', 'a'), 
     ('a', 'sea.')] 

預期輸出= [('live', 'in'), ('in', 'a'), ('a', 'yellow')]

我的代碼如下:它的工作原理在這種情況下,但在大型數據集以某種方式失敗。

All_elements_set1 = set([item for tuple in list1 for item in tuple]) 

All_elements_set2 = set([item for tuple in list2 for item in tuple]) 


common_set = All_elements_set1 & All_elements_set2 

new_list = [(i,v) for i,v in list1 if i (in common_set and v in common_set)] 

print new_list 
+2

也解釋一下,「大型數據集中的某種失敗」是什麼意思?你能給個例子嗎? – 2013-02-27 08:48:27

回答

3
In [39]: from itertools import chain 

In [40]: list1 = [('We', 'all'), ('all', 'live'), ('live', 'in'), ('in', 'a'), 
    ...:   ('a', 'yellow'), ('yellow', 'submarine.')] 
    ...: 
    ...: list2 = [('A', 'live'), ('live', 'yellow'), ('yellow', 'submarine'), 
    ...:   ('submarine', 'lifeform'), ('lifeform', 'in'), ('in', 'a'), 
    ...:   ('a', 'sea.')] 
    ...: 

In [41]: elems = set(chain.from_iterable(list2)) 

In [42]: [tup for tup in list1 if elems.issuperset(tup)] 
Out[42]: [('live', 'in'), ('in', 'a'), ('a', 'yellow')] 
+2

+1不錯的一個..很難從OP問題的問題來理解 – avasal 2013-02-27 08:53:21

+1

'elems.issuperset(t)'可以代替所有的東西定時它們),它更明顯是什麼 – Volatility 2013-02-27 09:00:27

+0

@Volatility - 謝謝,這是一個很好的改進。 – root 2013-02-27 09:06:09

0

基本上,你不需要做一組列表1中的元素。所有你需要的,如果檢查,在列表1每個元組,它們的元素是否在列表2元組的一些...

list1 = [('We', 'all'), ('all', 'live'), ('live', 'in'), ('in', 'a'), 
     ('a', 'yellow'), ('yellow', 'submarine.')] 

list2 = [('A', 'live'), ('live', 'yellow'), ('yellow', 'submarine'), 
     ('submarine', 'lifeform'), ('lifeform', 'in'), ('in', 'a'), 
     ('a', 'sea.')] 

Elements_set2 = set([item for tuple in list2 for item in tuple]) 

print [(i,v) for i,v in list1 if (i in Elements_set2 and v in Elements_set2)] 

如你不給瞭解您的代碼失敗的情況下的細節,不能檢查是否該一個在你失敗的例子上工作。

相關問題