Python 中的 intersection_update() 查找 n 个数组中的公共元素

pythonserver side programmingprogramming

在本文中,我们将学习 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()及其实现。


相关文章