📜  Python – 测试元组是否包含 K

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

Python – 测试元组是否包含 K

有时,在使用Python时,我们可能会遇到一个问题,其中我们有一条记录,我们需要检查它是否包含 K。这种问题在数据预处理步骤中很常见。让我们讨论可以执行此任务的某些方式。

方法 #1:使用any() + map() + lambda
上述功能的组合可用于执行此任务。在此,我们使用 any() 检查任何元素,逻辑扩展由 map() 和 lambda 完成。

# Python3 code to demonstrate working of
# Test if Tuple contains K
# using any() + map() + lambda
  
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# initialize K 
K = 6
  
# Test if Tuple contains K
# using any() + map() + lambda
res = any(map(lambda ele: ele is K, test_tup))
  
# printing result
print("Does tuple contain any K value ? : " + str(res))
输出 :
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain any K value ? : True

方法#2:使用循环
可以使用循环以及使用蛮力构造来执行此任务。我们只是遍历元组,当我们遇到 K 时,我们将 flag 设置为 True 并中断。

# Python3 code to demonstrate working of
# Test if Tuple contains K
# Using loop
  
# initialize tuple
test_tup = (10, 4, 5, 6, 8)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# initialize K 
K = 6
  
# Test if Tuple contains K
# Using loop
res = False 
for ele in test_tup:
    if ele == K:
        res = True
        break
  
# printing result
print("Does tuple contain any K value ? : " + str(res))
输出 :
The original tuple : (10, 4, 5, 6, 8)
Does tuple contain any K value ? : True