在列表中找到公共元素

6

我有一个单词列表的列表,命名为 wordlist,如下所示:

[['dog', 'cat', 'sheep', 'rabbit', 'kiss', 'time'], ['cow', 'pig', 'bomb', 'cat', 'sheep', 'cake', 'boy', 'new']]

我希望找到所有子列表中的公共元素。因此,我想要上述列表的输出结果应该是:
['cat', 'sheep']

为了实现这一目标,我使用下面的代码创建了一组集合:
sets = set(tuple(row) for row in wordlist)

这个集合长这样:
{('cow', 'pig', 'bomb', 'cat', 'sheep', 'cake', 'boy', 'new'), ('dog', 'cat', 'sheep', 'rabbit', 'kiss', 'time')}

每个列表中可以有任意数量的单词,且列表的数量也可以任意。因此,我可能会得到任意数量的不均衡集合。我知道可以使用交集方法比较两个集合,但是如何跨多个集合进行比较,以仅返回共有项?

2个回答

14

您正在错误地使用set。您可以像这样使用:

my_list = [['dog', 'cat', 'sheep', 'rabbit', 'kiss', 'time'], ['cow', 'pig', 'bomb', 'cat', 'sheep', 'cake', 'boy', 'new']]

# convert list of list to list of sets
my_sets = map(set, my_list)

# perform intersection on each set present in list
common_items = set.intersection(*my_sets)

这可以写成一行:

common_items = set.intersection(*map(set, my_list))

common_items所持有的值将是:

{'sheep', 'cat'}

这里是提供与稍微更高效的方法产生相同结果的解决方案:

#                              v no need to type-cast sub-lists to `set` here
set(my_list[0]).intersection(*my_list[1:])

# OR,
# set(my_list[0]).intersection(*my_list)
# as intersection of set with itself returns the same set

由于set.intersection接受所有可迭代对象,因此无需将所有子列表强制转换为集合。


1
最简单的方法是使用 map() 将输入转换为集合,然后使用 set.intersection 找到它们的共同之处:
>>> data = [['dog', 'cat', 'sheep', 'rabbit', 'kiss', 'time'],
            ['cow', 'pig', 'bomb', 'cat', 'sheep', 'cake', 'boy', 'new']]
>>> set.intersection(*map(set, data))
{'sheep', 'cat'}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接