a = {'a', 'b', 'c'} b = {'d', 'e', 'f'}
How do I add the above two sets? I expect the result:
c = {'a', 'b', 'c', 'd', 'e', 'f'}
使用以下方法计算集合的并集:
c = a | b
集合是唯一值的无序序列。a | b,或 a.union(b),是两个集合的并集ーー也就是说,一个新集合中包含两个集合中的所有值。这是一类名为“ set operation”的操作,Python 集合类型配备了这种操作。
a | b
a.union(b)
您可以使用 .update()将 set b组合成 set a:
.update()
b
a
a = {'a', 'b', 'c'} b = {'d', 'e', 'f'} a.update(b) print(a)
要创建一个新的集合,你首先需要 .copy()的第一个集合:
.copy()
c = a.copy() c.update(b) print(c)
使用 c 中 a 和 b 的 union ()的结果注意: sort ()用于打印排序后的输出
a = {'a','b','c'} b = {'d','e','f'} c = a.union(b) print(sorted(c)) #this will print a sorted list
或者简单地打印 a 和 b 的未排序联合
print(c) #this will print set c
如果你想减去两组,我测试了这个:
A={'A1','A2','A3'} B={'B1','B2'} C={'C1','C2'} D={'D1','D2','D3'} All_Staff=A|B|C|D All_Staff=sorted(All_Staff.difference(B)) print("All of the stuff are:",All_Staff)
结果:
All of the stuff are: ['A1', 'A2', 'A3', 'C1', 'C2', 'D1', 'D2', 'D3']
使用 unpack:
>>> c = {*a, *b} >>> c {'a', 'b', 'c', 'd', 'e', 'f'}