Python|记录交叉点
有时,在使用元组时,我们可能会遇到需要两条记录的相似特征的问题。这种类型的应用程序可以进入数据科学领域。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用set() + "&" operator
可以使用 XOR运算符对集合提供的对称差分功能来执行此任务。到 set 的转换是由 set() 完成的。
# Python3 code to demonstrate working of
# Records Intersection
# 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))
# Records Intersection
# Using set() + "&" operator
res = tuple(set(test_tup1) & set(test_tup2))
# printing result
print("The similar elements from tuples are : " + str(res))
输出 :
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The similar elements from tuples are : (4, 5)
方法#2:使用intersection() + set()
这是与上述方法类似的方法,不同之处在于我们使用内置函数代替 &运算符来执行过滤不同元素的任务。
# Python3 code to demonstrate working of
# Records Intersection
# Using intersection() + 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))
# Records Intersection
# Using intersection() + set()
res = tuple(set(test_tup1).intersection(set(test_tup2)))
# printing result
print("The similar elements from tuples are : " + str(res))
输出 :
The original tuple 1 : (3, 4, 5, 6)
The original tuple 2 : (5, 7, 4, 10)
The similar elements from tuples are : (4, 5)