Python Set的此内置函数可帮助我们获取两个集合之间的对称差,该差等于两个集合中任一集合中存在的元素,但并非这两个集合共有。让我们看一下两组之间的symmetric_difference的维恩图。
对称差异标记为绿色
如果存在set_A和set_B,则它们之间的对称差将等于set_A和set_B的并集,而两者之间没有交集。
// Takes a single parameter that has to be // a set and returns a new set which is the // symmetric difference between the two sets. set_A.symmetric_difference(set_B)
例子:
Input:set_A = {1, 2, 3, 4, 5} set_B = {6, 7, 3, 9, 4} Output: {1, 2, 5, 6, 7, 9} Explanation:The common elements {3, 4} are discarded from the output. Input: set_A = {"ram", "rahim", "ajay", "rishav", "aakash"} set_B = {"aakash", "ajay", "shyam", "ram", "ravi"} Output:{"rahim", "rishav", "shyam", "ravi"} Explanation:The common elements {"ram", "ajay", "aakash"} are discarded from the final set
在此程序中,我们将尝试找出两组之间的对称差:
# Python code to find the symmetric_difference
# Use of symmetric_difference() method
set_A = {1, 2, 3, 4, 5}
set_B = {6, 7, 3, 9, 4}
print(set_A.symmetric_difference(set_B))
输出:
{1, 2, 5, 6, 7, 9}
还有另一种方法,通过使用运算符“ ^”来获得两组之间的对称差。例:
# Python code to find the Symmetric difference
# using ^ operator.
# Driver Code
set_A = {"ram", "rahim", "ajay", "rishav", "aakash"}
set_B = {"aakash", "ajay", "shyam", "ram", "ravi"}
print(set_A ^ set_B)
输出:
{'shyam', 'ravi', 'rahim', 'rishav'}
# One more example Python code to find
# the symmetric_difference use of
# symmetric_difference() method
A = {'p', 'a', 'w', 'a', 'n'}
B = {'r', 'a', 'o', 'n', 'e'}
C = {}
print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
print(A.symmetric_difference(C))
print(B.symmetric_difference(C))
# this example is contributed by sunny6041
输出:
set(['e', 'o', 'p', 'r', 'w']) set(['e', 'o', 'p', 'r', 'w']) set(['a', 'p', 'w', 'n']) set(['a', 'r', 'e', 'o', 'n'])
注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 Python Set | symmetric_difference()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。