Python-检查两个列表是否有任何共同点
在使用python列表处理数据时,我们遇到一种情况,我们需要知道两个列表是否完全不同或它们是否具有任何共同点。可以通过将两个列表中的元素与以下描述的方法进行比较来找出。
在中使用
在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.