Python|检查元组中是否存在元素
有时,在处理数据时,我们可能会遇到需要检查我们正在处理的数据是否具有特定元素的问题。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是执行此任务的蛮力方法。在此,我们遍历元组并检查每个元素是否是我们的,如果找到我们返回 True。
# Python3 code to demonstrate working of
# Check if element is present in tuple
# using loop
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
# initialize N
N = 6
# Check if element is present in tuple
# using loop
res = False
for ele in test_tup :
if N == ele :
res = True
break
# printing result
print("Does tuple contain required value ? : " + str(res))
输出 :
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True
方法 #2:使用 in运算符
使用 in运算符是执行此任务的最 Pythonic 方式。它是单行的,建议执行此任务。
# Python3 code to demonstrate working of
# Check if element is present in tuple
# Using in operator
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
# initialize N
N = 6
# Check if element is present in tuple
# Using in operator
res = N in test_tup
# printing result
print("Does tuple contain required value ? : " + str(res))
输出 :
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain required value ? : True