Python|检查元组的元组中是否存在元素
有时我们使用的数据是元组的形式,而且我们经常需要查看嵌套的元组。这可以解决的常见问题是在数据预处理中寻找缺失的数据或 NA 值。让我们讨论可以执行此操作的某些方式。
方法 #1:使用any()
any
函数都用于执行此任务。如果元素作为元组元素存在,它只会一一测试。如果元素存在,则返回 true,否则返回 false。
# Python3 code to demonstrate
# test for values in tuple of tuple
# using any()
# initializing tuple of tuple
test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))
# printing tuple
print ("The original tuple is " + str(test_tuple))
# using any()
# to test for value in tuple of tuple
if (any('geeksforgeeks' in i for i in test_tuple)) :
print("geeksforgeeks is present")
else :
print("geeksforgeeks is not present")
输出 :
The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best'))
geeksforgeeks is present
方法 #2:使用itertools.chain()
chain
函数测试所有中间元组的所需值,然后如果所需值出现在任何搜索的元组中,则返回 true。
# Python3 code to demonstrate
# test for values in tuple of tuple
# using itertools.chain()
import itertools
# initializing tuple of tuple
test_tuple = (("geeksforgeeks", "gfg"), ("CS_Portal", "best"))
# printing tuple
print ("The original tuple is " + str(test_tuple))
# using itertools.chain()
# to test for value in tuple of tuple
if ('geeksforgeeks' in itertools.chain(*test_tuple)) :
print("geeksforgeeks is present")
else :
print("geeksforgeeks is not present")
输出 :
The original tuple is (('geeksforgeeks', 'gfg'), ('CS_Portal', 'best'))
geeksforgeeks is present