파이썬 목록을 사용하여 데이터를 조작하는 동안 두 목록이 서로 완전히 다른지 또는 공통 요소가 있는지 알아야 하는 상황이 발생합니다. 이는 두 목록의 요소를 아래에 설명된 접근 방식과 비교하여 알 수 있습니다.
인 사용
for 루프에서 in 절을 사용하여 요소가 목록에 있는지 여부를 확인합니다. 이 논리를 확장하여 첫 번째 목록에서 요소를 선택하고 두 번째 목록에서 요소의 존재를 확인하여 목록의 요소를 비교합니다. 따라서 이 검사를 수행하기 위해 for 루프가 중첩됩니다.
예
#Declaring lists
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
list3=[12,3,12,15,14,15,17]
list4=[12,42,41,12,41,12]
# In[23]:
#Defining function to check for common elements in two lists
def commonelems(x,y):
common=0
for value in x:
if value in y:
common=1
if(not common):
return ("The lists have no common elements")
else:
return ("The lists have common elements")
# In[24]:
#Checking two lists for common elements
print("Comparing list1 and list2:")
print(commonelems(list1,list2))
print("\n")
print("Comparing list1 and list3:")
print(commonelems(list1,list3))
print("\n")
print("Comparing list3 and list4:")
print(commonelems(list3,list4)) 위의 코드를 실행하면 다음과 같은 결과가 나옵니다.
출력
Comparing list1 and list2: The lists have common elements Comparing list1 and list3: The lists have no common elements Comparing list3 and list4: The lists have common elements
세트 사용
두 목록에 공통 요소가 있는 경우 찾는 또 다른 방법은 집합을 사용하는 것입니다. 세트에는 순서 없는 고유 요소 모음이 있습니다. 그래서 우리는 목록을 집합으로 변환한 다음 주어진 집합을 결합하여 새 집합을 만듭니다. 공통 요소가 있는 경우 새 세트가 비어 있지 않습니다.
예
list1=['a',4,'%','d','e']
list2=[3,'f',6,'d','e',3]
# Defining function two check common elements in two lists by converting to sets
def commonelem_set(z, x):
one = set(z)
two = set(x)
if (one & two):
return ("There are common elements in both lists:", one & two)
else:
return ("There are no common elements")
# Checking common elements in two lists for
z = commonelem_set(list1, list2)
print(z)
def commonelem_any(a, b):
out = any(check in a for check in b)
# Checking condition
if out:
return ("The lists have common elements.")
else:
return ("The lists do not have common elements.")
print(commonelem_any(list1, list2)) 위의 코드를 실행하면 다음과 같은 결과가 나옵니다.
출력
('There are common elements in both lists:', {'d', 'e'})
The lists have common elements.