Python学习笔记7—集合

set 拥有类似 dict 的特点:可以用{}花括号来定义;其中的元素没有序列,也就是是非序列类型的数据;而且,set 中的元素不可重复,这就类似 dict 的键.

>>> s1 = set("Keven")
>>> s1
set(['K', 'n', 'e', 'v'])
>>> type(s1)
<type 'set'>
>>> s3 = set(["name","age","gender"])
>>> s3
set(['gender', 'age', 'name']

除了用set() 来创建集合。还可以使用{} 的方式,但是这种方式不提倡使用,通过{}无法创建含有 list/dict 元素的 set.

>>> s2 = {"name",32}
>>> s2
set([32, 'name'])

无法创建list,direct的set

>>> s3 = {["name","age"]}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

不变集合

>>> f_set=frozenset("Keven")
>>> f_set
frozenset(['K', 'n', 'e', 'v'])
>>> f_set.add("python")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

 

posted @   头痛不头痛  阅读(212)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示
主题色彩