Python – 检查元组是否只包含 K 个元素
有时,在使用Python元组时,我们可能会遇到需要测试任何元组是否包含来自集合 K 个元素的元素的问题。这种问题非常普遍,并且在许多领域都有应用,例如 Web 开发和日常编程。让我们讨论一下可以完成此任务的某些方法。
Input : test_tuple = (1, 2, 3, 2, 1, 2), K = [1, 2, 3, 4]
Output : True
Input : test_tuple = (1, 2, 3), K = [1, 2]
Output : False
方法 #1:使用all()
这是可以执行此任务的方式之一。在此,我们使用内置函数all() 检查元组中是否存在仅来自特定数字集的所有元素。
# Python3 code to demonstrate working of
# Check if Tuple contains only K elements
# Using all()
# initializing tuple
test_tuple = (3, 5, 6, 5, 3, 6)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing K elements
K = [3, 6, 5]
# Check if Tuple contains only K elements
# Using all()
res = all(ele in K for ele in test_tuple)
# printing result
print("Does tuples contains just from K elements : " + str(res))
输出 :
The original tuple : (3, 5, 6, 5, 3, 6)
Does tuples contains just from K elements : True
方法 #2:使用set()
这是解决此问题的另一种方法。在此,我们将元组转换为设置,然后测试与查询 K 元素的小于和等于关系。
# Python3 code to demonstrate working of
# Check if Tuple contains only K elements
# Using set()
# initializing tuple
test_tuple = (3, 5, 6, 5, 3, 6)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing K elements
K = [3, 6, 5]
# Check if Tuple contains only K elements
# Using all()
res = set(test_tuple) <= set(K)
# printing result
print("Does tuples contains just from K elements : " + str(res))
输出 :
The original tuple : (3, 5, 6, 5, 3, 6)
Does tuples contains just from K elements : True