在 Python 中查找列表列表中的公共元素
pythonserver side programmingprogramming更新于 2025/12/27 10:52:17
可能有一个列表,其内部元素也是列表。在这种情况下,我们可能会遇到需要找出这些内部列表中的公共元素的需求。在本文中,我们将找到实现此目的的方法。
使用 map 和交集
交集是一个简单的数学概念,用于查找不同集合之间的公共元素。Python 具有 set 方法,该方法返回一个包含两个或多个集合之间相似性的集合。因此,我们首先通过 map 函数将列表的元素转换为集合,然后将 set 方法应用于所有转换后的列表。
示例
listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]
# 给定列表
print("Given list of lists : \n",listA)
# Applying intersection
res = list(set.intersection(*map(set, listA)))
# 结果
print("The common elements among inners lists : ",res)
输出
运行上述代码得到以下结果 −
Given list of lists : [['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]] The common elements among inners lists : ['Tue', 7]
使用reduce和lambda
我们还可以在python中应用reduce函数。此函数用于将作为参数传递给它的给定函数应用于传递的序列中提到的所有列表元素。在将set应用于每个嵌套列表后,lambda函数通过迭代每个嵌套列表来找出共同元素。
示例
from functools import reduce
listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]
# 给定列表
print("Given list of lists : \n",listA)
# Applying reduce
res = list(reduce(lambda i, j: i & j, (set(n) for n in listA)))
# 结果
print("The common elements among inners lists : ",res)
输出
运行上述代码得到以下结果 −
Given list of lists : [['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]] The common elements among inners lists : ['Tue', 7]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

