一、集合的特性
1、集合是无序的,不能通过下标进行索引
2、集合有天生去重的功能
二、集合的运算
set1 = {1, 2, 3, 4, 5} set2 = {5, 6, 7, 8, 9} set_union = set1.union(set2) #并集,将set2合并到set1,并去掉重复元素 set_union1 = set1 | set2 set_intersection = set1.intersection(set2) #交集 set_intersection1 = set1 & set2 set_diff = set1.difference(set2) #差集 set_diff1 = set1 - set2 print('set1和set2的并集为: ', set_union) print('set1 | set2 = ', set_union1) print('set1和set2的交集为: ', set_intersection) print('set1 & set2 = ', set_intersection1) print('set1和set2的差集为: ', set_diff) print('set1 - set2 = ', set_diff1)
查看结果:
set1和set2的并集为: {1, 2, 3, 4, 5, 6, 7, 8, 9}
set1 | set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
set1和set2的交集为: {5}
set1 & set2 = {5}
set1和set2的差集为: {1, 2, 3, 4}
set1 - set2 = {1, 2, 3, 4}
三、集合的其他方法
set1 = set() #set()初始化集合, set1= {}初始化为字典 set1 = {1,2,3,4,5} set2 = {3,4} bool1 = set1.issubset(set2) #判断set1是否为set2的子集 bool2 = set1.issuperset(set2) #判断set1是否为set2的父集 bool3 = set1.isdisjoint(set2) #判断是否有交集,没有交集返回True set1 = {1,2,3,4,5} set1.add(6) #添加元素 set1.remove(1) #删除指定元素 set1.pop() #随机删除一个元素 set1.discard(4) #删除指定元素