Python中两个数组的交集(Lambda表达式和过滤器函数)
在本文中,我们将借助Lambda表达式和过滤器功能来学习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表达式和过滤器函数及其实现,了解了Python中两个数组的交集。