如果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
也解释一下,“大型数据集中的某种失败”是什么意思?你能给个例子吗? – 2013-02-27 08:48:27