集合:不同的元素(不可hash)组合在一起的就叫做集合,去掉重复的,以空字符返回,无序的
可以分为可变集合和不可变集合(frozenset)
创建:
s = set('gm gyx')
print(s){' ', 'x', 'm', 'g', 'y'}
集合不能作为字典的键,
s = frozenset('gm gyx')
查询:
for i in s:
print(i)
print('g' in s)
添加:
s.add('u') 添加一个元素
s.update('ups') 把参数作为一个序列,更新到set里,这里会添加3个元素,参数里有重复的话会去重,参数为列表的话,那就把列表里的元素做一个结合一个元素添加
s.remove('u') 把U元素移除
s.pop()随机删除一个元素
s.clear() 清空
del s
集合类型操作符
in ,not in
等价 print(set('alxe')==set('alxeeexl'))
子集
print(set('axle') < set('axleda'))
交集
s1.intersection(s2) in s1 and in s2 s1&s2
反向交集。对称差集
s1.symmetric_difference(s2) not in s1 and not in s2 两边都不在 s1^s2
并集
s1.union(s2) 取全部且去重 s1|s2
差集
a.diffence(b) in a but in b : a-b
a.isuperset(b) a是否完全包含b a > b
a.issubset(b) a是否完全属于b a < b