📜  Python - 测试列表中是否存在任何集合元素

📅  最后修改于: 2022-05-13 01:54:37.838000             🧑  作者: Mango

Python - 测试列表中是否存在任何集合元素

给定一个集合和列表,任务是编写一个Python程序来检查列表中是否存在任何集合元素。

例子:

方法 #1:使用any()

在这里,我们迭代集合的所有元素并检查列表中是否出现任何元素。 any()为任何元素匹配条件返回 true。

Python3
# Python3 code to demonstrate working of
# Test if any set element exists in List
# Using any()
  
# initializing set
test_set = {6, 4, 2, 7, 9, 1}
  
# printing original set
print("The original set is : " + str(test_set))
  
# initializing list
test_list = [6, 8, 10]
  
# any() checking for any set element in check list
res = any(ele in test_set for ele in test_list)
  
# printing result
print("Any set element is in list ? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test if any set element exists in List
# Using & operator
  
# initializing set
test_set = {6, 4, 2, 7, 9, 1}
  
# printing original set
print("The original set is : " + str(test_set))
  
# initializing list
test_list = [6, 8, 10]
  
# & operator checks for any common element
res = bool(test_set & set(test_list))
  
# printing result
print("Any set element is in list ? : " + str(res))


输出:

The original set is : {1, 2, 4, 6, 7, 9}
Any set element is in list ? : True

方法#2:使用&运算符

在此,我们通过 set 和 list 之间的使用和操作来检查任何元素,如果有任何元素匹配,则结果为 True。

蟒蛇3

# Python3 code to demonstrate working of
# Test if any set element exists in List
# Using & operator
  
# initializing set
test_set = {6, 4, 2, 7, 9, 1}
  
# printing original set
print("The original set is : " + str(test_set))
  
# initializing list
test_list = [6, 8, 10]
  
# & operator checks for any common element
res = bool(test_set & set(test_list))
  
# printing result
print("Any set element is in list ? : " + str(res))

输出:

The original set is : {1, 2, 4, 6, 7, 9}
Any set element is in list ? : True