集合(set)是一个无序的不重复元素序列。 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。 set 可变集合,set里可以传列表 字典 字符串 集合 frozenset 不可变集合
定义:s={}/s=set()
>>> s=set([1,2,3,2,1,2]) #集合里面传列表,另外集合有去重功能 >>> s {1, 2, 3} >>> s={4,5,6} >>> type(s) <class ‘set‘> >>> s=set({1:2,3:4}) #集合里面传字典 >>> s {1, 3} >>> s=set("abcabc") #集合里面传字符串 >>> s {‘a‘, ‘c‘, ‘b‘} >>> >>> s=set({1,2,3,2,3,4}) #集合里面传集合 >>> s {1, 2, 3, 4} >>> #添加元素 #set是无序的 添加的内容不固定顺序 不一定加在哪个位置 >>> s. add("fgh") #add把内容当做一个字符串来添加 >>> s {1, 2, 3, 4, ‘fgh‘} >>> s. update("fgh") #update把内容拆开添加 >>> s {1, 2, 3, 4, ‘h‘, ‘g‘, ‘f‘, ‘fgh‘} >>> #移除元素 >>> s {‘l‘, ‘o‘, ‘e‘} >>> s. remove("e") #将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误 >>> s {‘l‘, ‘o‘} >>> >>> s. discard("o") #也是移除集合中的元素,且如果元素不存在,不会发生错误 >>> s {‘l‘} >>> s. pop() #返回并删除 ‘l‘ >>> s set() >>> #集合可以用len求长度 copy复制 clear清空 >>> s=set("hello") >>> s {‘l‘, ‘h‘, ‘o‘, ‘e‘} >>> len(s) 4 >>> s1=s. copy() #操作copy的内容两个集合互不影响 >>> s1 {‘l‘, ‘h‘, ‘o‘, ‘e‘} >>> s {‘l‘, ‘h‘, ‘o‘, ‘e‘} >>> s1. remove("e") >>> s1 {‘l‘, ‘h‘, ‘o‘} >>> s {‘l‘, ‘h‘, ‘o‘, ‘e‘} >>> s. clear() >>> s set() >>> #遍历(set不能按位置遍历) >>> for i in s: ... print(i) ... h fgh a g c f >>> for id,value in enumerate(s): ... print(id,value) ... 0 h 1 fgh 2 a 3 g 4 c 5 f #set可以跟list和tuple互转 >>> s {‘l‘, ‘o‘} >>> list(s) [‘l‘, ‘o‘] >>> tuple(s) (‘l‘, ‘o‘) >>> set(s) {‘l‘, ‘o‘} >>> #求集合 >>> s1 {‘l‘, ‘h‘, ‘o‘} >>> s=set("ho") >>> s {‘h‘, ‘o‘} >>> s1 &s #&交集 {‘h‘, ‘o‘} >>> s1 |s #|并集 {‘h‘, ‘l‘, ‘o‘} >>> s1 -s #-差集 {‘l‘} >>> 用集合实现第一题: >>> import random >>> a= list(range(1,101)) >>> a=set(a) >>> rand_num =random.randint(0,99) >>> rand_num 44 >>> b=list(range(1,101))[:rand_num]+list(range(1,101)[rand_num+1:]) >>> b [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] >>> len(b) 99 用函数计算集合:
>>> s={1,2,3} >>> s1={3,4,5} >>> s.difference(s1)#差集函数,差集是有方向的 {1, 2} >>> s1.difference(s) {4, 5} >>> s.intersection(s1)#交集 {3} >>> s.union(s1)#并集 {1, 2, 3, 4, 5} >>>
集合大于 等于 比的是个数 >>> {1}>{1} False >>> {1}=={1} True >>> {1,2}>{1} True >>> {1,2}>{1} 包含和不包含 >>> {2,3,4}>{5} False >>> {2,3,4}>{2} True 超集 子集 完全相等集合 函数 >>> {2}. issubset({1,2,3}) #子集,判断指定集合({2})是否为该方法参数集合({1,2,3})的子集 True >>> {2}. issuperset({1,2,3}) #包含,判断该方法的参数集合是否为指定集合的子集,判断{1,2,3}是否是{2}的子集 False >>> {1,2,3,4}.issuperset({1,2,3}) True in ,not in 判断在不在 >>> 1 in {1,2,3} True >>> 22 not in {1,2,3} True 不可变集合 不可变集合,除了内容不能更改外,其他功能及操作跟可变集合set一样 a=frozenset([1,2,3]) a.pop() >>> a=frozenset([1,2,3]) >>> a.pop() #当改变不可变集合里面的内容时,会报错 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: ‘frozenset‘ object has no attribute ‘pop‘ >>>声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did170917