目录
1.获得两个集合的并集
初级:遍历这两个集合,将元素添加到一个新的集合中
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
union_set = set()
for i in set_a:
union_set.add(i)
for i in set_b:
union_set.add(i)
print(union_set)
# {1, 2, 3, 4, 7, 8, 9}
进阶:Python中的集合为两个集合的合并提供了一个union() 方法(或update()方法,或 | 符号)
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
union_set = set_a.union(set_b)
print(union_set)
# {1, 2, 3, 4, 7, 8, 9}
print(set_a|set_b)
# {1, 2, 3, 4, 7, 8, 9}
set_a.update(set_b)
print(set_a)
# {1, 2, 3, 4, 7, 8, 9}
2.获取两个集合的交集
初级:遍历寻找两个集合之间的共同元素
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
intersection_set = set()
for i in set_a:
if i in set_b:
intersection_set.add(i)
print(intersection_set)
# {8, 1}
进阶:Python 为两个集合的交集提供了intersection() 方法(或intersection_update()方法,或&符号)
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
intersection_set = set_a.intersection(set_b)
print(intersection_set)
# {8, 1}
print(set_a&set_b)
# {8, 1}
set_a.intersection_update(set_b)
print(set_a)
# {8, 1}
3.获得两个集合的差集
初级:遍历寻找一个集合中另一集合没有的元素
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
difference_set = set()
for i in set_a:
if i not in set_b:
difference_set.add(i)
print(difference_set)
进阶:Python 为两个集合的差集提供了difference()方法(或difference_update()方法,或-符号)
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
difference_set = set_a.difference(set_b)
print(difference_set)
# {2, 4}
print(set_a-set_b)
# {2, 4}
set_a.difference_update(set_b)
print(set_a)
# {2, 4}
4.获得两个集合的对称差集
初级:遍历两个集合并集中交集没有的元素
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
union_set = set()
intersection_set = set()
symmetric_difference_set = set()
for i in set_a:
union_set.add(i)
for i in set_b:
union_set.add(i)
for i in set_a:
if i in set_b:
intersection_set.add(i)
for i in union_set:
if i not in intersection_set:
symmetric_difference_set.add(i)
print(symmetric_difference_set)
# {2, 3, 4, 7, 9}
进阶:Python 为两个集合的对称差集提供了symmetric_difference()方法(或symmetric_difference_update()方法,或^符号)
set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}
symmetric_difference_set = set_a.symmetric_difference(set_b)
print(symmetric_difference_set)
# {2, 3, 4, 7, 9}
print(set_a^set_b)
# {2, 3, 4, 7, 9}
set_a.symmetric_difference_update(set_b)
print(set_a)
# {2, 3, 4, 7, 9}