Python |检查两个列表是否至少有一个公共元素

给定两个列表a、b。检查两个列表中是否至少有一个元素是相同的。

null

例如:

Input : a = [1, 2, 3, 4, 5]
        b = [5, 6, 7, 8, 9]
Output : True

Input : a=[1, 2, 3, 4, 5]
        b=[6, 7, 8, 9]
Output : False

方法1:遍历列表

使用 穿越 在两个列表中,我们可以检查其中是否至少存在一个公共元素。在遍历两个列表时,如果我们发现其中有一个元素是公共的,则返回true。在完成遍历和检查之后,如果没有相同的元素,则返回false。

# Python program to check
# if two lists have at-least
# one element common
# using traversal of list
def common_data(list1, list2):
result = False
# traverse in the 1st list
for x in list1:
# traverse in the 2nd list
for y in list2:
# if one common
if x = = y:
result = True
return result
return result
# driver code
a = [ 1 , 2 , 3 , 4 , 5 ]
b = [ 5 , 6 , 7 , 8 , 9 ]
print (common_data(a, b))
a = [ 1 , 2 , 3 , 4 , 5 ]
b = [ 6 , 7 , 8 , 9 ]
print (common_data(a, b))


输出:

True 
False

方法2:使用集合和属性

使用 集合的性质 ,如果至少存在一个公共元素,则set(a)&set(b)返回一个正整数,如果它不包含任何正整数,则返回0。所以我们在集合a中插入a,在集合b中插入b,然后检查集合a和集合b是否为正整数。

# Python program to check
# if two lists have at-least
# one element common
# using set and property
def common_member(a, b):
a_set = set (a)
b_set = set (b)
if (a_set & b_set):
return True
else :
return False
a = [ 1 , 2 , 3 , 4 , 5 ]
b = [ 5 , 6 , 7 , 8 , 9 ]
print (common_member(a, b))
a = [ 1 , 2 , 3 , 4 , 5 ]
b = [ 6 , 7 , 8 , 9 ]
print (common_member(a, b))


输出:

True 
False

方法3:使用集合交集

使用 集合交叉点 内置函数。一套。交叉点(b_集)如果至少有一个公共元素,则返回正整数,否则返回0。我们在集合a中插入a,在集合b中插入b,然后检查集合a。交叉点(b_集),并根据值返回。

# Python program to check
# if two lists have at-least
# one element common
# using set intersection
def common_member(a, b):
a_set = set (a)
b_set = set (b)
if len (a_set.intersection(b_set)) > 0 :
return ( True )
return ( False )
a = [ 1 , 2 , 3 , 4 , 5 ]
b = [ 5 , 6 , 7 , 8 , 9 ]
print (common_member(a, b))
a = [ 1 , 2 , 3 , 4 , 5 ]
b = [ 6 , 7 , 8 , 9 ]
print (common_member(a, b))


输出:

True 
False
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享