标签:一个 line date sub 系统 讲解 mod 类型 删除
一、集合的创建:
set1={1,2,‘barry‘} set2={1,2,‘barry‘} print(set1,set2) #{1, 2, ‘barry‘} {1, 2, ‘barry‘}
2、集合的增
add
set1={‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} set1.add(‘taibai‘) print(set1) #{‘taibai‘, ‘wusir‘, ‘ritian‘, ‘alex‘, ‘barry‘, ‘egon‘}
update():在对集合增加元素的时候是迭代增加到集合中的。
set1={‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} set1.add(‘taibai‘) set1.update(‘A‘) print(set1) #{‘egon‘, ‘alex‘, ‘taibai‘, ‘wusir‘, ‘barry‘, ‘A‘, ‘ritian‘} set1.update(‘老师‘) print(set1) #{‘师‘, ‘ritian‘, ‘A‘, ‘老‘, ‘egon‘, ‘taibai‘, ‘wusir‘, ‘alex‘, ‘barry‘} set1.update([1,2,3]) print(set1) #{‘alex‘, ‘A‘, 1, 2, ‘ritian‘, 3, ‘师‘, ‘老‘, ‘taibai‘, ‘egon‘, ‘barry‘, ‘wusir‘}
3、集合的删
set1={‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} set1.remove(‘alex‘) # 删除一个元素 print(set1) #{‘wusir‘, ‘ritian‘, ‘egon‘, ‘barry‘}
set1={‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} set1.pop() # 随机删除一个元素 print(set1) #{‘egon‘, ‘alex‘, ‘wusir‘, ‘ritian‘}
set1={‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} set1.clear() # 清空集合 print(set1) # set()
set1={‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} del set1 # 清空集合 print(set1) # Traceback (most recent call last): # File "C:/Pythonbc/课堂/作业讲解7.py", line 112, in <module> # print(set1) # NameError: name ‘set1‘ is not defined
#这是由于使用del删除集合set1之后,set1已经不存在了,所以系统找不到会报错
二、集合的其他操作
1、交集。(&或者intersection)
set1={1,2,3,4,5} set2={3,4,5,6,7} print(set1 & set2) print(set2.intersection(set1)) # {3, 4, 5} # {3, 4, 5}
2、并集。(|或者union)
set1={1,2,3,4,5}
set2={3,4,5,6,7}
print(set1 | set2)
print(set1.union(set2))
# {1, 2, 3, 4, 5, 6, 7}
# {1, 2, 3, 4, 5, 6, 7}
3、反交集。(^或者symmetric_difference)
set1={1,2,3,4,5} set2={3,4,5,6,7} print(set1 ^ set2) print(set2.symmetric_difference(set1)) # {1, 2, 6, 7} # {1, 2, 6, 7}
4、差集。(-或者difference)
set1={1,2,3,4,5} set2={3,4,5,6,7} print(set1 - set2) print(set2.difference(set1)) # {1, 2} # {6, 7}
5、子集与超集
set1={1,2,3} set2={1,2,3,4,6,5} print(set1<set2) # True print(set1.issubset(set2)) # True #这两个都是说明set1是set2的子集 print(set2>set1) # True print(set2.issuperset(set1)) # True print(set1>set2) # False print(set1.issuperset(set2)) # False
#这几个说明只有当set1中所有的元素都存在于set2中时结果才为真
三、frozense不可变集合,让集合变成不可变类型。
a=frozenset(‘barry‘) print(a,type(a)) #frozenset({‘r‘, ‘a‘, ‘y‘, ‘b‘}) <class ‘frozenset‘>
标签:一个 line date sub 系统 讲解 mod 类型 删除
原文地址:http://www.cnblogs.com/hzqblog/p/7753146.html