python中的集合 (set) 的创建和使用

描述:

集合(set)是一个无序的不重复元素序列。集合和列表非常相似

集合和列表的不同点:

  • 集合中只能存储不可变对象
  • 集合中存储的对象是无序(不是按照元素的插入顺序保存)
  • 集合中不能也不会出现重复的元素

创建集合:

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

方法一:使用{ }来创建集合

s = {
    
    10,3,5,1,2,1,2,3,1,1,1,1}
print(s) # {1, 2, 3, 5, 10}
print(type(s)) # <class 'set'>

从上边的代码可以看出,集合中储存的对象是无序的,不会出现重复的元素(可用于去重)

集合中只能存储不可变对象
a = {
    
    [1,2,3],[4,6,7]}
print(a) # 报错 TypeError: unhashable type: 'list'

方法二:使用 set() 函数来创建集合

创建一个空集合
s = set() 
print(s) # set()
print(type(s)) # <class 'set'>

通过set()来将序列和字典转换为集合,使用set()将字典转换为集合时,只会包含字典中的键

s = set([1,3,4,4,5,1,1,2,3,4,5])
print(s) # {1, 2, 3, 4, 5}

s = set('hello')
print(s) # {'h', 'o', 'l', 'e'}

s = set({
    
    'a':1,'b':2,'c':3})
print(s) # {'a', 'c', 'b'}

集合的运用:

  1. 使用 innot in 来检查集合中的元素
s = {
    
    'a','b',1,2,3,1}
print('c' in s)   # False
print(1 in s)     # True
print(2 not in s) # False
  1. 使用 len() 来获取集合中元素的数量
s = {
    
    'a','b',1,2,3,1}
print(s)      # {1, 2, 3, 'a', 'b'}
print(len(s)) # 5
  1. add() 向集合中添加元素,如果元素已存在,则不进行任何操作。
s = {
    
    'a','b',1,2,3,1}
s.add(3)
s.add(10)
s.add('hello')
print(s) # {1, 2, 3, 10, 'hello', 'b', 'a'}
  1. update() 将一个集合中的元素添加到当前集合中,update()可以传递序列或字典作为参数,字典只会使用键
s1 = {
    
    1,2,3}
s2 = set("hello")
print(s2)     # {'l', 'o', 'e', 'h'}

s1.update(s2) # 将一个集合中的元素添加到当前集合中
print(s1)     # {'h', 1, 2, 3, 'e', 'o', 'l'}
s1 = {
    
    1,2,3}
s1.update((10,20,30,40)) # 传递一个序列作为参数
print(s1)     # {1, 2, 3, 40, 10, 20, 30}
s1 = {
    
    1,2,3}
s1.update({
    
    100:'aa',200:'bb',300:'cc',400:'dd'}) # 传递一个字典作为参数
print(s1)  # {400, 1, 2, 3, 100, 200, 300}
  1. pop() 随机删除该集合中的一个元素,并返回
s = {
    
    4, 2, 3, 100, 40, 'o', 'a', 'h',}
result = s.pop()
print(result) # 2
  1. remove(x) 删除集合中的指定元素x
s = {
    
    4, 2, 3, 100, 40, 'o', 'a', 'h',}
s.remove(100)
print(s) # {2, 3, 4, 'h', 40, 'o', 'a'}
  1. clear() 清空集合
s = {
    
    4, 2, 3, 100, 40, 'o', 'a', 'h',}
s.clear()
print(s) # set() 空集合

猜你喜欢

转载自blog.csdn.net/weixin_43974265/article/details/104960203
今日推荐