Python - 检查两个列表是否有共同元素
在使用 Python 列表操作数据时,我们经常会遇到需要知道两个列表是否完全不同或者它们是否有任何共同元素的情况。这可以通过比较两个列表中的元素来实现,以下描述了几种方法。
使用 in
在 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.
广告