Python中的交集更新()在n个数组中查找公共元素
在本文中,我们将学习Python中的iintersection_update()来找出n个数组中的公共元素。
问题是给我们一个包含列表的数组,找到给定数组中的所有公共元素?
算法
1.Initializingres with the first list inside the array 2.Iterating through the array containing lists 3.Updating the res list by applying intersection_update() function to check the common elements. 4.Finally returning the list and display the output by the help of the print statement.
现在让我们看一下它的实现
示例
def commonEle(arr):
# initialize res with set(arr[0])
res = set(arr[0])
# new value will get updated each time function is executed
for curr in arr[1:]: # slicing
res.intersection_update(curr)
return list(res)
# Driver code
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中的iintersection_update()来查找n个数组中的公共元素及其实现。
热门推荐
5 足球队祝福语简短
10 分别祝福语简短情侣短句
11 关于开车的祝福语简短
12 许嵩生日祝福语简短
13 祝福语大全简短赞美同学
14 生病祝福语简短文案
15 分手祝福语简短短句
16 新年祝福语简短给孩子
17 诗词文案祝福语简短精辟
18 大雪生日祝福语大全简短