定义:


  • 由不同元素组成的集合,集合中是一组无序排列的可hash值,可作为字典的key
  • v= {1,2,3,4,5,6}
  • v = set(["umbrella","umbrella","s"]),用set定义会自动产生一个for循环,去掉集合内重复的元素再输出,比如前面这个集合就会输出s和umbrella
  • 属于可变类型,可增加可删除,通过frozenset() 可定义为不可变集合


特性:

1.不同元素组成,可尝试用add()在集合里加元素,若新加的元素集合中没有则输出,有则不重复输出


v= {1,2,3,4,5,6} v.add(3) v.add(9) print(v)



2.无序

3.组合中的元素必须是不可变的(字符串、数字、元组,反之列表不可)


功能:


  • add() 添加元素,若新加的元素集合中没有则输出,有则不重复输出。且一次只能更新一个值,如想一次更新多个要使用update()


v= {1,2,3,4,5,6} v.add(3) v.add(9) print(v)




  • clear() 清除元素


v= {1,2,3,4,5,6} v.clear() print(v)




  • copy() 拷贝



  • pop() 随机删除,每次随机删除一个(因为集合无序)


v= {1,2,3,4,5,6,"umbrella"} v.pop() print(v)




  • remove() 可以删除指定元素,集合中无指定元素时报错


v= {1,2,3,4,5,6,"umbrella"} v.remove("umbrella") print(v)




  • discard() 可删除指定元素,集合中无指定元素时也不会报错


v= {1,2,3,4,5,6,"umbrella"} v.discard("umbrel") print(v)




  • intersection或者&,求两个集合的交集


v1 = [1,2,3,4,5,6,"umbrella"] v2 = ["umbrella","rain"] v1_s = set(v1) v2_s = set(v2) print(v1_s.intersection(v2_s)) print(v1_s & v2_s)




  • union()或者 | ,求并集,去掉重复的元素


v1 = [1,2,3,4,5,6,"umbrella"] v2 = ["umbrella","rain"] v1_s = set(v1) v2_s = set(v2) print(v1_s.union(v2_s)) print(v1_s | v2_s)




  • difference()或者 - ,求差集


v1 = [1,2,3,4,5,6,"umbrella"] v2 = ["umbrella","rain"] v1_s = set(v1) v2_s = set(v2) print(v1_s.difference(v2_s)) print(v1_s - v2_s) print(v2_s.difference(v1_s)) print(v2_s - v1_s)




  • symmetric_difference()或者 ^ ,交叉补集,并集再减去交集,即先合到一起再去掉共有的部分


v1 = [1,2,3,4,5,6,"umbrella"] v2 = ["umbrella","rain"] v1_s = set(v1) v2_s = set(v2) print(v1_s.symmetric_difference(v2_s)) print(v1_s ^ v2_s)




  • difference_update(),差集,去掉交集后留下的集合


v1 = [1,2,3,4,5,6,"umbrella"] v2 = ["umbrella","rain"] v1_s = set(v1) v2_s = set(v2) v = v1_s - v2_s print(v) v1_s.difference_update(v2_s) print(v1_s)




  • intersection_update() 求交集后更新集合


v1 = [1,2,3,4,5,6,"umbrella"] v2 = ["umbrella","rain"] v1_s = set(v1) v2_s = set(v2)  v1_s.intersection_update(v2_s) print(v1_s)




  • isdisjoint() 判断是否没有共有的部分


v1 = [1,2,3,4,5,6,"umbrella"] v2 = ["umbrella","rain"] v1_s = set(v1) v2_s = set(v2) v3 = {1,2,3} v4 = {4,5,6}  print(v1_s.isdisjoint(v2_s)) print(v3.isdisjoint(v4))




  • issubset() ,是否为子集(相反:issuperset() 是否为父集)


v1 = [1,2,3,4,5,6,"umbrella"]
v2 = ["umbrella","rain"]
v1_s = set(v1)
v2_s = set(v2)
v3 = {1,2,3}
v4 = {1,2}
print(v1_s.issubset(v2_s))
print(v4.issubset(v3))
print(v3.issuperset(v4))




  • update() 更新集合,将原集合中没有的元素加进去;可用于一次更新多个元素(可迭代的都能传,比如列表可以)。PS:注意区分并集union() ,union新建立了一个并集,并未覆盖原来的集合,而update未新建集合而是覆盖了原集合。


v1 = {1,2,3} v2 = {1,2,5} v1.update(v2) print(v1) print(v1.union(v2))