Computer >> Máy Tính >  >> Lập trình >> Python

Giao điểm của hai mảng trong Python (biểu thức Lambda và hàm lọc)

Trong bài viết này, chúng ta sẽ tìm hiểu về giao điểm của hai mảng trong Python với sự trợ giúp của hàm lọc và biểu thức Lambda.

Vấn đề là chúng ta được cung cấp hai mảng, chúng ta phải tìm ra các phần tử chung trong cả hai mảng.

Thuật toán

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.

Bây giờ chúng ta hãy xem cách triển khai của nó:

Ví dụ

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)

Đầu ra

Intersection of arr1 & arr2 is: ['o', 'i', 't']

Kết luận

Trong bài viết này, chúng ta đã tìm hiểu về giao điểm của hai mảng trong Python với sự trợ giúp của hàm lọc và biểu thức Lambda cũng như cách triển khai của nó.