2013-02-27 128 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)] 

如你不给了解您的代码失败的情况下的细节,不能检查是否该一个在你失败的例子上工作。

相关问题