集合

创建集合

创建集合使⽤ {} 或 set() , 但是如果要创建空集合只能使⽤ set() ,因为 {} ⽤来创建空字典。

  1. s1 = {10, 20, 30, 40, 50}
  2. print(s1)
  3. s2 = {10, 30, 20, 10, 30, 40, 30, 50}
  4. print(s2)
  5. s3 = set('abcdefg')
  6. print(s3)
  7. s4 = set()
  8. print(type(s4)) # set
  9. s5 = {}
  10. print(type(s5)) # dict

特点:

  1. 集合可以去掉重复数据;

  2. 集合数据是⽆序的,故不⽀持下标

常⻅操作

增加数据

add()
  1. s1 = {10, 20}
  2. s1.add(100)
  3. s1.add(10)
  4. print(s1) # {100, 10, 20}

因为集合有去重功能,所以,当向集合内追加的数据是当前集合已有数据的话,则不进⾏任何操

作。

update(), 追加的数据是序列。
  1. s1 = {10, 20}
  2. # s1.update(100) # 报错
  3. s1.update([100, 200])
  4. s1.update('abc')
  5. print(s1)

删除数据

remove(),删除集合中的指定数据,如果数据不存在则报错。
  1. s1 = {10, 20}
  2. s1.remove(10)
  3. print(s1)
  4. s1.remove(10) # 报错
  5. print(s1)

discard(),删除集合中的指定数据,如果数据不存在也不会报错
  1. s1 = {10, 20}
  2. s1.discard(10)
  3. print(s1)
  4. s1.discard(10)
  5. print(s1)

pop(),随机删除集合中的某个数据,并返回这个数据
  1. s1 = {10, 20, 30, 40, 50}
  2. del_num = s1.pop()
  3. print(del_num)
  4. print(s1)

查找数据

in:判断数据在集合序列

not in:判断数据不在集合序列
  1. s1 = {10, 20, 30, 40, 50}
  2. print(10 in s1)
  3. print(10 not in s1)