📜  Python|查找元组中的不同元素

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

Python|查找元组中的不同元素

有时,在处理元组时,我们可能会遇到需要两条记录的不同特征的问题。这种类型的应用程序可以进入数据科学领域。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用set() + "^" operator

可以使用 XOR运算符对集合提供的对称差分功能来执行此任务。到 set 的转换由set()完成。

# Python3 code to demonstrate working of
# Dissimilar elements in tuples
# Using set() + "^" operator
  
# initialize tuples
test_tup1 = (3, 4, 5, 6)
test_tup2 = (5, 7, 4, 10)
  
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Dissimilar elements in tuples
# Using set() + "^" operator
res = tuple(set(test_tup1) ^ set(test_tup2))
  
# printing result
print("The Dissimilar elements from tuples are : " + str(res))
输出 :
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The Dissimilar elements from tuples are : (3, 6, 7, 10)

方法 #2:使用symmetric_difference() + set()

这是与上述方法类似的方法,不同之处在于我们使用内置函数代替异或运算符来执行过滤不同元素的任务。

# Python3 code to demonstrate working of
# Dissimilar elements in tuples
# Using symmetric_difference() + set()
  
# initialize tuples
test_tup1 = (3, 4, 5, 6)
test_tup2 = (5, 7, 4, 10)
  
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Dissimilar elements in tuples
# Using symmetric_difference() + set()
res = tuple(set(test_tup1).symmetric_difference(set(test_tup2)))
  
# printing result
print("The Dissimilar elements from tuples are : " + str(res))
输出 :
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The Dissimilar elements from tuples are : (3, 6, 7, 10)