|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
集合和字典都是一对花括号,区别是字典有映射关系,而集合没有
- >>> num = {} # 创建一个空字典
- >>> type(num)
- <class 'dict'>
- >>> num2 = {1,2,3,4,5} # 用花括号,没有映射的称为集合
- >>> type(num2)
- <class 'set'> # set 就是集合
- >>> num2 = {1,2,3,4,5,5,4,3,2} # 集合会自动去重
- >>> num2
- {1, 2, 3, 4, 5}
- >>>num2[2] # 会报错,集合没有索引
复制代码
如何创建一个集合
一种是直接把一堆元素用花括号括起来
一种是使用set()工厂函数
- >>> set1 = set([1,2,3,4,5,5]) # 用set() 函数创建一个集合,set()的参数可以是一个列表,一个元组 或字符串都行
- >>> set1
- {1, 2, 3, 4, 5}
- >>> num1 = [1,2,3,4,5,5,3,1,0]
- >>> temp = []
- >>> for each in num1: # 把num1列表去重,然后放到temp列表
- if each not in temp:
- temp.append(each)
- >>> temp
- [1, 2, 3, 4, 5, 0]
- >>> num1 = list(set(num1)) # 用set去重,但set无顺序,去重完了以列表返回, 如果你的列表关注前后顺序,那么用set要谨慎,因为会打乱顺序
- >>> num1
- [0, 1, 2, 3, 4, 5]
复制代码
如何访问集合中的值:
可以使用for把集合中的数据一个个读取出来
可以通过in和not in 判断一个元素是否在集合中已经存在
- >>> num2
- {1, 2, 3, 4, 5}
- >>> 1 in num2 # 成员操作符in 判断
- True
- >>> '1' in num2
- False
复制代码- >>> num2.add(6) # add() 添加一个集合元素
- >>> num2
- {1, 2, 3, 4, 5, 6}
- >>> num2.remove(5) # remove() 删除一个集合元素
- >>> num2
- {1, 2, 3, 4, 6}
复制代码
不可变集合
frozen:冰冻的,冻结的
- >>> num3 = frozenset([1,2,3,4,5]) # 不可变的集合
- >>> num3.add(0) # 不能添加,也不能更改
- Traceback (most recent call last):
- File "<pyshell#139>", line 1, in <module>
- num3.add(0)
- AttributeError: 'frozenset' object has no attribute 'add'
复制代码 |
|