gpt4 book ai didi

python - 在 python 中,如果两个列表都包含公共(public)元素,则从两个元组列表中选择元组

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:16 24 4
gpt4 key购买 nike

如果 list1 中的元素在 list2 中存在或常见,我想从 list1 的元组中创建一个新的元组列表。

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

最佳答案

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')]

关于python - 在 python 中,如果两个列表都包含公共(public)元素,则从两个元组列表中选择元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15107541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com