python - 在列表列表中查找共同元素

标签 python list set

我有一个名为 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')}

每个列表可以有任意数量的单词,并且可以有任意数量的列表。所以我最终可能会得到任意数量的不均匀集合。我知道我可以使用交集方法比较两个集合,但如何跨多个集合进行比较以仅返回常见项目?

最佳答案

您正在使用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 接受所有可迭代对象,因此无需对所有子列表进行类型转换来设置。

关于python - 在列表列表中查找共同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41925415/

相关文章:

python - 如何使用 sklearn.datasets.make_classification 生成给定范围内的合成数据?

python - 将yield语句转换为Python中的生成器表达式

css - 有序列表中的无序列表

python - 根据 Pandas 中的索引范围组合列的行

r - 两个阶跃函数的交集

python - 两个字符串列表的交集

python - 如何获取作为字典的数据帧的列的值

Python2.7 : Extract slice from a list based on a pattern in a Pythonic way

python - 如何找到两个 Pandas DataFrame 之间的差异

python - 如何添加或删除 Chrome 扩展 "after"selenium 网络驱动程序已实例化/定义