📜  Python设置 symmetric_difference_update()

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

Python设置 symmetric_difference_update()

两个集合的对称差是元素集合在其中一个集合中但不在这两个集合中。

对称差

对称差异标记为绿色
symmetric_difference() 方法返回一个包含两个集合的对称差的新集合。 symmetric_difference_update() 方法使用集合的对称差来更新调用 symmetric_difference_update() 的集合。

代码 1

Python
# Python code to demonstrate working of
# symmetric_difference_update()
 
A = {'p', 'a', 'w', 'a', 'n'}
B = {'r', 'a', 'o', 'n', 'e'}
 
# result is always none.
result = A.symmetric_difference_update(B)
 
print('A = ', A)
print('B = ', B)
print('result = ', result)


Python
# Python code to demonstrate working of
# symmetric_difference_update()
 
A = {'s', 'u', 'n', 'n', 'y'}
B = {'b', 'u', 'n', 'n', 'y'}
 
# result is always none.
result = A.symmetric_difference_update(B)
 
print('A = ', A)
print('B = ', B)
print('result = ', result)


Python
# Python code to demonstrate working of
# symmetric_difference_update()
 
A = {1, 2, 3, 4, 5, 6}
B = [4, 5, 7, 8]
 
# passing argument as list
 
A.symmetric_difference_update(B)
print("A =", A)
 
A = {2, 4, 6, 8}
B = (i for i in range(2, 6))
 
# passing argument as generator object
 
A.symmetric_difference_update(B)
print("A=", A)


Python
# Python code to demonstrate working of
# symmetric_difference_update()
 
A = {1, 2, 3, 4, 5}
B = [[1, 2, 3], 4, 5]
 
# error as b contain one element as list(unhashable object)
 
A.symmetric_difference_update(B)
print("A =", A)


输出:

('A = ', set(['e', 'o', 'p', 'r', 'w']))
('B = ', set(['a', 'r', 'e', 'o', 'n']))
('result = ', None)



代码 2

Python

# Python code to demonstrate working of
# symmetric_difference_update()
 
A = {'s', 'u', 'n', 'n', 'y'}
B = {'b', 'u', 'n', 'n', 'y'}
 
# result is always none.
result = A.symmetric_difference_update(B)
 
print('A = ', A)
print('B = ', B)
print('result = ', result)

输出:

('A = ', set(['s', 'b']))
('B = ', set(['y', 'b', 'u', 'n']))
('result = ', None)



代码 3:

Python

# Python code to demonstrate working of
# symmetric_difference_update()
 
A = {1, 2, 3, 4, 5, 6}
B = [4, 5, 7, 8]
 
# passing argument as list
 
A.symmetric_difference_update(B)
print("A =", A)
 
A = {2, 4, 6, 8}
B = (i for i in range(2, 6))
 
# passing argument as generator object
 
A.symmetric_difference_update(B)
print("A=", A)
输出
('A =', set([1, 2, 3, 6, 7, 8]))
('A=', set([3, 5, 6, 8]))





代码 4:

Python

# Python code to demonstrate working of
# symmetric_difference_update()
 
A = {1, 2, 3, 4, 5}
B = [[1, 2, 3], 4, 5]
 
# error as b contain one element as list(unhashable object)
 
A.symmetric_difference_update(B)
print("A =", A)

输出

Traceback (most recent call last):
  File "/home/1b4e24cadc3fabcd5f90141964a60e9b.py", line 9, in 
    A.symmetric_difference_update(B)
TypeError: unhashable type: 'list'