python 中的 intersection_update() 用來找到 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 個數組中的公共元素以及它的實現。

更新於:07-Aug-2019

134 瀏覽量

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.