当前位置: 首页 > news >正文

3.6 集合

集合(set) --- 只存储字典的key

1.集合的定义

            -格式: {元素}

            -特征:

                1.无序      2.无重复        3.可为任意类型

1.集合的定义

#- 创建空集合  

'''set = {}

print(type(set))     <class 'dict'> 因为空的 {} 被用来表示空字典,而不是空集合。'''



set1 = set()

print(set1)             #set()

print(type(set1))       #<class 'set'>

# - 创建一个元素集合

set1 = {10}

print(set1)             #{10}

print(type(set1))       #<class 'set'>

# - 创建多个元素集合

set1 = {"username","password",10.0,98,98}

print(set1)         #{10.0, 'password', 'username', 98} 证明了集合的无序和无重复性

# - 案例:对某个字符串去重

string1 = "hellow world"

print(set(string1))             #{'h', 'r', ' ', 'w', 'd', 'e', 'o', 'l'}

2.集合的常用方法

            Clear,remove,copy

            add:添加元素,如果元素重复,不能添加,涉及到hash算法

            difference:差集

            intersection:交集

            union:并集

            update:更新集合,合并集合

            discard:移除元素,但是元素如果不存在,则不做任何操作  

 2.测试集合的常用函数

# - add

print(set1.add("age"))          #None  无返回值

print(set1)                     #{98, 10.0, 'password', 'age', 'username'}



# - update  更新并合并集合,如果重复则覆盖

print(set1.update({"hellow world"}))  #输出一个字典会打印一整个元素

print(set1)                 #{'hellow world', 98, 'age', 10.0, 'password', 'username'}



print(set1.update("hellow world"))    #输出一个字符串会拆分开并去重加入集合

print(set1)                 #{'e', 'hellow world', 98, 'age', 10.0, 'l', 'o', 'r', 'd', 'password', 'w', ' ', 'h', 'username'}



# - discard    删除一个元素

set2 = {"wzw",23,22,"hello"}

print(set2.discard("hello"))

print(set2)             #{'wzw', 23, 22}



# -intersection 交集

set_x = {1,2,3,4,5}

set_y = {1,2,3,6,7}

print(set_x.intersection(set_y))            #{1, 2, 3}



# -union  并集

print(set_x.union(set_y))                   #{1, 2, 3, 4, 5, 6, 7}



# -difference  差集

print(set_x.difference(set_y))              #{4, 5}     x关于y的差集

print(set_y.difference(set_x))              #{6, 7}     y关于x的差集

相关文章:

  • SpringBoot Starter自定义:创建可复用的自动配置模块
  • 基于QtC++音乐播放器whisper语音转文字歌词解析
  • 奇趣点播系统测试报告
  • can‘t set boot order in virtualbox
  • 深入解析B站androidApp接口:从bilibili.api.ticket.v1.Ticket/GetTicket到SendMsg的技术分析
  • java -jar指定类加载
  • 【2025蓝桥杯省赛填空压轴题-pythonA组和研究生组】Ipv6 解析(四维dp)
  • MySQL存储引擎:存储什么意思?引擎什么意思?存储引擎是什么?在MySQL中有什么作用?
  • 【CHNS】随访时间 整理
  • dnf install openssl失败的原因和解决办法
  • 第七届浙江省大学生网络与信息安全竞赛决赛Unserialize深度解析 1.0
  • 设计模式-观察者模式
  • warning C4828: 文件包含在偏移 0x194 处开始的字符,该字符在当前源字符集中无效(代码页 65001)
  • pyqt环境配置
  • hevc编码芯片学习-VLSI实现
  • aes密钥如何生成固定的16位呢?
  • 大表查询的优化方案
  • 【ComfyUI】蓝耘元生代 | ComfyUI深度解析:高性能AI绘画工作流实践
  • 详细介绍7大排序算法
  • Nginx用途以及好处:
  • 云南昭通黄吉庆寻子29年终团聚:儿子在同事鼓励下回乡认亲
  • 研究|和去年相比,人们使用AI的需求发生了哪些变化?
  • 刺激视网膜可让人“看”到全新颜色
  • 阿联酋首个AI博士项目设立,助力人才培养与科技转型
  • 新闻1+1丨居民水电气计量收费乱象,如何治?
  • 跨市调任:李强已任河北唐山市检察院党组书记