Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

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에서 두 배열의 교차에 대해 배웠습니다.