1 #!/usr/bin/env python 2 #__author: hlc 3 #date: 2019/6/1 4 5 # set 集合 6 # 集合 把不同的元素组成一起形成集合,集合时python的基础类型 7 # 组成集合的成员不可重复 8 # a = [1,2,3,4,5,1,2,3,4,5,"a","a","a","b","b""b","c"] 9 # b = set(a) # 通过set关键字定义集合 10 # print(a) # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ‘a‘, ‘a‘, ‘a‘, ‘b‘, ‘bb‘, ‘c‘] 11 # print(b) # {1, 2, 3, 4, 5, ‘a‘, ‘bb‘, ‘c‘, ‘b‘} 12 13 # 集合对象时一个无序排列的可哈希的值:集合成员可以做字典的键 14 # a = [["asdf",1244],1,2,3,4,5,1,2,3,4,5,"a","a","a","b","b""b","c"] 15 # b = set(a) # TypeError: unhashable type: ‘list‘ 16 # print(b) 17 18 # 集合分类:可变集合,不可变集合 19 # 可变集合,可添加和删除元素,非可哈希,不能用作字典的键,也不能作为其他集合的元素,不可变集合与之相反 20 # a = [1,2,3] 21 # b = set(a) # TypeError: unhashable type: ‘set‘ 22 # c = {b:"sdf"} 23 24 # 集合的创建 25 # 由于集合没有自己的语法格式,只能通过集合的工厂方法set()和frozenset()创建 26 # s1 = set("asfd") 27 # s2 = frozenset("dsg") 28 # print(s1,type(s1)) # {‘f‘, ‘d‘, ‘a‘, ‘s‘} <class ‘set‘> 29 # print(s2,type(s2) # frozenset({‘d‘, ‘g‘, ‘s‘}) <class ‘frozenset‘> 30 31 # 访问集合 32 # 由于集合本身是无序的,所以不能为集合创建索引或切片操作,只能循环遍历或使用in、not in来访问或判断集合元素。 33 # s1 = set("asdfsd") 34 # print("a" in s1) # True 35 # s1[0] # TypeError: ‘set‘ object is not subscriptable 36 37 # for i in s1 : 38 # print(i) 39 # d 40 # s 41 # a 42 # f 43 44 # 更新集合,可使用以下内建方法更新: 45 # s1 = set("asdf") 46 # s1.add() 47 # s1.update() 48 # s1.remove() 49 # 只有可变集合才能更新 50 # s1 = frozenset("gdsfg") 51 # # s1.add() # AttributeError: ‘frozenset‘ object has no attribute ‘add‘ 52 53 # s2 = set("sdf") 54 # # s2.add("mmn") # {‘f‘, ‘mmn‘, ‘d‘, ‘s‘} 55 # s2.update("jkl") # {‘d‘, ‘l‘, ‘s‘, ‘k‘, ‘j‘, ‘f‘} 56 # print(s2) 57 58 # s1 = set(["asdf",325,"456"]) 59 # # s1.remove(325) # {‘456‘, ‘asdf‘} 60 # s1.pop() # {‘asdf‘, 325} 61 # s1.clear() # set() 62 # del s1 # NameError: name ‘s1‘ is not defined 63 # print(s1) 64 65 # 集合类型的操作符 66 # in ,not in 67 # 集合等价于不等价(==,!=) 68 # 子集 超集 69 # print(set("asd") == set("asdasd")) # True 70 # s = set("adsfas") 71 # s1 = set("ads") 72 # print("s" in s) # True 73 # print(s > s1) # True 74 75 # 联合(|) 联合(union)的操作与集合的or操作其实等价的,联合符号有个等价的方法,union() 76 # s1 = set("qewr") 77 # s2 = set("ghkj") 78 # s3 = s1|s2 79 # print(s3) # {‘e‘, ‘k‘, ‘r‘, ‘h‘, ‘w‘, ‘g‘, ‘q‘, ‘j‘} 80 # print(s1.union(s2)) # {‘e‘, ‘k‘, ‘r‘, ‘h‘, ‘w‘, ‘g‘, ‘q‘, ‘j‘} 81 82 a = set([1,2,3,4,5]) 83 b = set([4,5,6,7,8]) 84 85 # 交集 intersrction()等同于 a & b 86 # print(a.intersection(b)) # {4, 5} 87 # 并集 union 等同于 a | b 88 # print(a.union(b)) # {1, 2, 3, 4, 5, 6, 7, 8} 89 # 差集 difference 等同于a - b 90 # print(a.difference(b)) # {1, 2, 3} 91 # print(b.difference(a)) # {8, 6, 7} 92 # 对称差集(反向交集) symmetric_difference 等同于 a ^ b 93 # print(a.symmetric_difference(b)) # {1, 2, 3, 6, 7, 8} 94 # 父集,超集 95 # print(a.issuperset(b)) # > False 96 # 子集 97 # print(a.issubset(b)) # < False
原文地址:https://www.cnblogs.com/hlc-123/p/10960311.html
时间: 2024-10-11 08:02:52