当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Set symmetric_difference_update()用法及代码示例


设置 symmetric_difference_update() 方法

symmetric_difference_update() 方法用于获取两个集合中不常见的所有元素的列表并更新此集合(set1) 使用这些元素,或者我们可以说此方法用于更新此集合 (set1) 通过删除两个集合中共有的元素。

用法:

    set1.symmetric_difference_update(set2)

参数:

  • set2– 它表示要与此集合进行比较的另一个集合(set1)。

返回值:

这个方法的返回类型是<class 'NoneType'>, 它更新这个集合 (set1) 通过删除两个集合中共有的元素。

范例1:

# Python Set symmetric_difference_update() 
# Method with Example

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# printing sets before symmetric_difference_update()
print("Before calling symmetric_difference_update()...")
print("cars_1:", cars_1)
print("cars_2:", cars_2)

# symmetric_difference_update() method call
cars_1.symmetric_difference_update(cars_2)

# printing sets after symmetric_difference_update()
print("After calling symmetric_difference_update()...")
print("cars_1:", cars_1)
print("cars_2:", cars_2)

输出

Before calling symmetric_difference_update()...
cars_1:{'Audi', 'Lexus', 'Porsche'}
cars_2:{'Porsche', 'Mazda', 'Lincoln'}
After calling symmetric_difference_update()...
cars_1:{'Mazda', 'Audi', 'Lincoln', 'Lexus'}
cars_2:{'Porsche', 'Mazda', 'Lincoln'}

范例2:

# Python Set symmetric_difference_update() 
##Method with Example

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "ABC"}

# printing the results
print("Before calling symmetric_difference_update()...")
print("x:", x)
print("y:", y)
print("z:", z)

# printing the result of 
# symmetric_difference_update()
x.symmetric_difference_update(y)
y.symmetric_difference_update(z)
z.symmetric_difference_update(x)

# printing the results
print("After calling symmetric_difference_update()...")
print("x:", x)
print("y:", y)
print("z:", z)

输出

Before calling symmetric_difference_update()...
x:{'ABC', 'XYZ', 'PQR'}
y:{'ABC', 'XYZ', 'PQR'}
z:{'ABC', 'MNO', 'DEF'}
After calling symmetric_difference_update()...
x:set()y:{'XYZ', 'MNO', 'DEF', 'PQR'}
z:{'ABC', 'MNO', 'DEF'}


相关用法


注:本文由纯净天空筛选整理自 Python Set symmetric_difference_update() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。