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 中两个数组的交集及其实现。
广告