Python 中兩個陣列的交集(Lambda 表示式和 filter 函式)
在本文中,我們將藉助 Lambda 表示式和 filter 函數了解 Python 中兩個陣列的交集。
問題是我們給定兩個陣列,我們必須找出這兩個陣列中共同的元素。
演算法
1. Declaring an intersection function with two arguments. 2. Now we use the lambda expression to create an inline function for selection of elements with the help of filter function checking that element is contained in both the list or not. 3. Finally, we convert all the common elements in the form of a list by the help of typecasting. 4. And then we display the output by the help of the print statement.
現在讓我們來看看它的實現
示例
def interSection(arr1,arr2): # finding common elements
# using filter method oto find identical values via lambda function
values = list(filter(lambda x: x in arr1, arr2))
print ("Intersection of arr1 & arr2 is: ",values)
# Driver program
if __name__ == "__main__":
arr1 = ['t','u','t','o','r','i','a','l']
arr2 = ['p','o','i','n','t']
interSection(arr1,arr2)輸出
Intersection of arr1 & arr2 is: ['o', 'i', 't']
結論
在本文中,我們藉助 Lambda 表示式和 filter 函數了解了 Python 中兩個陣列的交集及其實現。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP