python语法_集合

集合:不同的元素(不可hash)组合在一起的就叫做集合,去掉重复的,以空字符返回,无序的

可以分为可变集合和不可变集合(frozenset)

创建:

s = set('gm gyx')

print(s){' ', 'x', 'm', 'g', 'y'}

集合不能作为字典的键,

s = frozenset('gm gyx')

查询:

for i in s:

  print(i)

扫描二维码关注公众号,回复: 4289412 查看本文章

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

猜你喜欢

转载自www.cnblogs.com/kevingm/p/10038397.html