1 #set里的元素是唯一的,即没有重复的,可以用set()函数,去数据的重复冗余 2 L = [1,1,1,2,4,5,6,7] 3 S = set(L) 4 print(S) #打印结果{1, 2, 4, 5, 6, 7},集合是以{}来表示的 5 #集合的运算 6 L_1 = [1,2,3,4] 7 L_2 = [3,4,5,6] 8 S_1 = set(L_1) 9 S_2 = set(L_2) 10 #交集 11 print(S_1.intersection(S_2)) #打印结果{3,4} 12 print(S_1&S_2) #和上一行等价 13 #并集 14 print(S_1.union(S_2)) #打印结果{1, 2, 3, 4, 5, 6} 15 print(S_1|S_2) 16 #差集 17 print(S_1.difference(S_2)) #打印结果{1,2},这个要注意谁和谁的差,结果是 18 # 调用函数的对象包含的元素而作为参数传入函数的对象不包含的元素 19 print(S_1-S_2) 20 #子集 21 print(S_1.issubset(S_2)) #结果False 22 #父集 23 print(S_1.issuperset(S_2)) #结果False 24 #查询 25 print(1 in S_1) #结果 True 26 print(1000 not in S_2) #结果 True 27 #删除 28 print(S_1.pop()) #随机删除,打印1,表示删掉了1这个元素 29 print(S_1) # {2, 3, 4} 30 S_1.remove(4) #指定删除4这个元素,如果4不存在,报错 31 print(S_1) #{2, 3} 32 S_1.discard(2) #指定删除3这个元素,和remove的区别,当2这个元素不存在时,不会报错 33 print(S_1) #{3} 34 #添加元素 35 S_1.add(1) #单个元素添加 36 print(S_1) #{1,3} 37 S_1.update(L) #直接加入应该列表 38 print(S_1) #{1, 2, 3, 4, 5, 6, 7}
python 基础(集合)
猜你喜欢
转载自www.cnblogs.com/planBinary/p/11703014.html
今日推荐
周排行