📜  Python|检查一个元组是否是其他元组的子集

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

Python|检查一个元组是否是其他元组的子集

有时,在使用Python时,我们可以处理不同的数据,我们可能需要解决检查一个子集是否属于另一个子集的问题。让我们讨论可以执行此任务的某些方式。

方法 #1:使用 issubset()
我们可以通过将元组类型转换为集合来解决这个问题,然后使用 issubset() 检查一个元组是否是另一个元组的子集。

# Python3 code to demonstrate working of
# Check if one tuple is subset of other
# using issubset()
  
# initialize tuples
test_tup1 = (10, 4, 5, 6)
test_tup2 = (5, 10)
  
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Check if one tuple is subset of other
# using issubset()
res = set(test_tup2).issubset(test_tup1)
  
# printing result
print("Is 2nd tuple subset of 1st ? : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 10)
Is 2nd tuple subset of 1st ? : True

方法 #2:使用all() + 生成器表达式
上述功能的组合也可以执行此任务。在此,我们使用表达式和 all() 检查一个元组的每个元素与另一个元组。

# Python3 code to demonstrate working of
# Check if one tuple is subset of other
# using all() + generator expression
  
# initialize tuples
test_tup1 = (10, 4, 5, 6)
test_tup2 = (5, 10)
  
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Check if one tuple is subset of other
# using all() + generator expression
res = all(ele in test_tup1 for ele in test_tup2)
  
# printing result
print("Is 2nd tuple subset of 1st ? : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 10)
Is 2nd tuple subset of 1st ? : True