1.集合的操作
2.文件的操作
1.集合的操作
定义:
1.不同元素组成,自动去重
2.无序
3.集合中的元素必须是不可变类型
1.集合的定义:
1 >>> s1 = set('abcd') #同s1 = set{'a','b','c','d'} 2 >>> s1 3 {'a', 'c', 'b', 'd'} 4 >>> t1 = set('cdef') 5 >>> t1 6 {'c', 'f', 'e', 'd'} 7 >>> un_set = set('hello') 8 >>> un_set 9 {'h', 'e', 'o', 'l'} 10 >>> #set是去重的 11 >>> un_set = frozenset(un_set) #定义只读集合 12 >>> un_set 13 frozenset({'h', 'e', 'o', 'l'}) 14 >>> #定义只读集合
2.集合的运算:
集合之间也可进行数学集合运算(例如:并集、交集等),可用相应的操作符或方法来实现。
#子集
>>> s1 = set('abcd') >>> t1 = set('cdef') >>> C = set('ab') >>> C>s1 #判断C是否为S1子集,用符号表示 False >>> C < s1 True >>> C.issubset(s1) #用方法.issubset()表示 True
#并集:集合中所有不同元素的集合
1 >>> s1 | t1 #符号表示 2 {'f', 'e', 'a', 'c', 'b', 'd'} 3 >>> s1.union(t1) #方法表示 4 {'f', 'e', 'a', 'c', 'b', 'd'}
#差集:s1和t1的差集,所有属于s1且不属于t1的元素集合
>>> s1 - t1 {'a', 'b'} >>> s1.difference(t1) {'a', 'b'}
#对称差集,s1和t1去掉公共元素后,其余元素的集合
1 >>> s1 ^ t1 2 {'f', 'e', 'a', 'b'} 3 >>> s1.symmetric_difference(t1) 4 {'f', 'e', 'a', 'b'}
3.集合的方法
参考博客,非常详细:https://www.cnblogs.com/suendanny/p/8597596.html