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

두 목록의 교차점을 찾는 Python 프로그램?

<시간/>

교차 연산은 List1과 List 2에서 모든 공통 요소를 가져와야 하고 모든 요소는 다른 세 번째 목록에 저장해야 함을 의미합니다.

List1::[1,2,3]
List2::[2,3,6]
List3::[2,3]

알고리즘

Step 1: input lists.
Step 2: first traverse all the elements in the first list and check with the elements in the second list.
Step 3: if the elements are matched then store in third list.

예시 코드

#Intersection of two lists 
def intertwolist(A, B):
   C = [i for i in A if i in B]
   return C
# Driver Code
A=list()
B=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Element of first list::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
print("Enter the Element of second list::")
for i in range(int(n)):
   k=int(input(""))
   B.append(k)
print("THE FINAL LIST IS ::>",intertwolist(A, B))

출력

Enter the size of the List ::5
Enter the Element of first list::
12
23
45
67
11
Enter the Element of second list::
23
45
88
11
22
THE FINAL LIST IS ::> [23, 45, 11]