Python 中的 intersection_update() 查找 n 个数组中的公共元素
pythonserver side programmingprogramming更新于 2025/9/21 22:36:17
在本文中,我们将学习 Python 中的 intersection_update() 查找 n 个数组中的公共元素。
问题是我们给定一个包含列表的数组,找出给定数组中的所有公共元素?
算法
1.使用数组中的第一个列表初始化res 2.遍历包含列表的数组 3.通过应用 intersection_update() 函数检查公共元素来更新 res 列表。 4.最后返回列表并通过 print 语句显示输出。
现在让我们看一下它的实现
示例
def commonEle(arr):
# 使用 set(arr[0]) 初始化 res
res = set(arr[0])
# 每次执行函数时都会更新新值
for curr in arr[1:]: # 切片
res.intersection_update(curr)
return list(res)
# 驱动代码
if __name__ == "__main__":
nest_list=[['t','u','o','r','i','a','l'], ['p','o','i','n','t'], ['t','u','o','r','i','a','l'], ['p','y','t','h','o','n']]
out = commonEle(nest_list)
if len(out) > 0:
print (out)
else:
print ('No Common Elements')
输出
['o', 't']
总结
本文我们学习了Python中查找n个数组中公共元素的iintersection_update()及其实现。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

