Python 程序检查两个列表是否至少有一个共同元素
programmingpythonserver side programming更新于 2025/3/14 12:28:17
要检查两个列表是否至少有一个共同元素,我们将循环遍历 list1 和 list2,并检查两个列表中是否至少有一个共同元素。列表是 Python 中最通用的数据类型,可以将其写为方括号之间的逗号分隔值(项目)列表。关于列表的重要一点是列表中的项目不必是同一类型。
假设我们有以下输入,即 2 个列表 -
[15, 45, 67, 30, 98] [10, 8, 45, 48, 30]
输出应如下,即两个列表至少有一个共同元素 -
Common Element Found
使用 for 循环检查两个列表是否至少有一个共同元素
我们使用嵌套 for 循环来检查用户输入的两个列表是否至少有两个元素。遍历两个列表并使用 if 语句找到共同元素。 input() 方法用于用户输入 −
示例
def commonFunc(A, B): c = "Common Element Not Found" # traverse in the 1st list for i in A: # traverse in the 2nd list for j in B: # if one common if i == j: c="Common Element Found" return c return c # Driver code A=list() B=list() n1=int(input("Enter the size of the first List =")) print("Enter the Element of the first List =") for i in range(int(n1)): k=int(input("")) A.append(k) n2=int(input("Enter the size of the second List =")) print("Enter the Element of the second List =") for i in range(int(n2)): k=int(input("")) B.append(k) print("Display Result =",commonFunc(A, B))
输出
Enter the size of the first List =5 Enter the Element of the first List = 15 45 67 30 98 Enter the size of the second List =7 Enter the Element of the second List = 10 8 45 48 30 86 67 Display Result = Common Element Found Enter the size of the first List =5 Enter the Element of the first List = 10 20 30 40 50 Enter the size of the second List =5 Enter the Element of the second List= 23 39 45 67 89 Display Result = Common Element Not Found
使用 set_intersection() 检查两个列表是否至少有一个共同元素
我们使用 set_intersection() 方法检查两个列表是否至少有一个共同元素。首先,将列表转换为集合,然后应用该方法查找共同元素 −
示例
def commonFunc(list1, list2): p_set = set(p) q_set = set(q) if len(p_set.intersection(q_set)) > 0: return True return False # First List p = [4, 10, 15, 20, 25, 30] print("List1 = ",p) # Second List q = [12, 24, 25, 35, 45, 65] print("List2 = ",q) print("Are common elements in both the lists? ",commonFunc(p, q))
输出
List1 = [4, 10, 15, 20, 25, 30] List2 = [12, 24, 25, 35, 45, 65] Are common elements in both the lists? True
使用 Set 检查两个列表是否至少有一个共同元素
在此示例中,我们使用 set() 方法将列表转换为集合,然后使用 & 运算符查找共同元素。因此,我们在这里没有使用 set_intersection() 方法 −
示例
def commonFunc(list1, list2): p_set = set(p) q_set = set(q) if (p_set & q_set): return True else: return False # First List p = [5, 10, 15, 20, 25, 30] print("List1 = ",p) # Second List q = [12, 20, 30, 35, 40, 50] print("List2 = ",q) print("Are common elements in both the lists? ",commonFunc(p, q))
输出
List1 = [5, 10, 15, 20, 25, 30] List2 = [12, 20, 30, 35, 40, 50] Are common elements in both the lists? True
上面,我们看到返回了 True,因为两个列表至少有一个共同元素。在此示例中,共同元素是 30。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

