📜  Python – 检查元组中是否存在任何列表元素

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

Python – 检查元组中是否存在任何列表元素

给定一个元组,检查其中是否存在任何列表元素。

方法#1:使用循环

在此,我们保留一个布尔变量,记录所有元素,如果找到,则返回 True,否则返回 False。

Python3
# Python3 code to demonstrate working of
# Check if any list element is present in Tuple
# Using loop
 
# initializing tuple
test_tup = (4, 5, 7, 9, 3)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing list
check_list = [6, 7, 10, 11]
 
res = False
for ele in check_list:
     
    # checking using in operator
    if ele in test_tup :
        res = True
        break
 
# printing result
print("Is any list element present in tuple ? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Check if any list element is present in Tuple
# Using any()
 
# initializing tuple
test_tup = (4, 5, 7, 9, 3)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing list
check_list = [6, 7, 10, 11]
 
# generator expression is used for iteration
res = any(ele in test_tup for ele in check_list)
 
# printing result
print("Is any list element present in tuple ? : " + str(res))


输出
The original tuple is : (4, 5, 7, 9, 3)
Is any list element present in tuple ? : True

方法 #2:使用 any()

这将返回 True,如果在元组中找到列表的任何元素,则使用 in 运算符进行测试。

Python3

# Python3 code to demonstrate working of
# Check if any list element is present in Tuple
# Using any()
 
# initializing tuple
test_tup = (4, 5, 7, 9, 3)
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# initializing list
check_list = [6, 7, 10, 11]
 
# generator expression is used for iteration
res = any(ele in test_tup for ele in check_list)
 
# printing result
print("Is any list element present in tuple ? : " + str(res))
输出
The original tuple is : (4, 5, 7, 9, 3)
Is any list element present in tuple ? : True