ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
>[success] # set 集合 ~~~ 1.set 集合表现形式{ } 是无序排列的,当去除list 列表中的重复数据时可以用set 2.他里面的元素必须是不可变的数据类型,也就是说里面不能是列表字典等 ~~~ >[danger] ##### set 表现形式 ~~~ # 集合的两种表现形式 list1=set([1,2,3,4]) list2={1,6,7,5} ~~~ >[danger] ##### add -- 添加 ~~~ # 添加的位置随机因为set 是无序的,不能添加列表等可变类型 set1 = {"1","2","3"} set1.add("添加内容") print(set1) 打印结果: {'1', '3', '添加内容', '2'} ~~~ >[danger] ##### update -- 添加可迭代类型数据 ~~~ set1 = {"1","2","3"} set1.update(['4','5']) print(set1) 打印结果: {'1', '4', '5', '2', '3'} ~~~ >[danger] ##### pop -- 随机删除 ~~~ # 随机删除返回值是删除对象 set1 = {"1","2","3"} a = set1.pop() print(set1, a) 打印结果: {'2', '3'} 1 ~~~ >[danger] ##### remove -- 指定删除对象 ~~~ # 无返回值 set1 = {"1","2","3"} set1.remove('2') print(set1) 打印结果: {'3', '1'} ~~~ >[danger] ##### clear -- 清除集合中内容 ~~~ set1 = {"1","2","3"} set1.clear() print(set1) 打印结果: set() ~~~ >[danger] ##### del -- 删除内存 ~~~ set1 = {"1","2","3"} del set1 ~~~ >[danger] ##### 利用循环查询 ~~~ set1 = {"1","2","3"} for i in set1: print(i) ~~~ >[danger] ##### 去重复 ~~~ list_1 = [1, 4, 5, 7, 3, 6, 7, 9] # 去重set list_1 = set(list_1) # 打印去重后效果,类型 print(list_1, type(list_1)) 打印结果: {1, 3, 4, 5, 6, 7, 9} <class 'set'> ~~~ >[danger] ##### & / intersection -- 求交集 ~~~ set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} set3 = set1 & set2 print(set3) # {4, 5} print(set1.intersection(set2)) # {4, 5} 打印结果: {4, 5} ~~~ >[danger] ##### | / union 求并集 ~~~ set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7,8} print(set2.union(set1)) # {1, 2, 3, 4, 5, 6, 7,8} 打印结果: {1, 2, 3, 4, 5, 6, 7,8} ~~~ >[danger] ##### 独有的 ~~~ set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 - set2) # {1, 2, 3} #set1独有的 print(set1.difference(set2)) # {1, 2, 3} 打印结果: {1, 2, 3} ~~~