集合
1. 基本定义语法
num = {1,2,3,4,5,6}
num
# 输出:{1,2,3,4,5,6}
type(num)
# 输出:<class 'set'>
2. 用工厂函数set()定义集合
- 可以把,字符串(str)、元组(tuple)、序列(list)、集合(set)、字典(dict)作为一个整体直接转换成集合
- 字典只把keys变成一个集合
# 字符串
set1 = set('hello word')
set1
# 输出:{' ', 'e', 'd', 'h', 'o', 'l', 'r', 'w'}
# 元组
set2 = set((1,2,3,4))
set2
# 输出:{1, 2, 3, 4}
# 序列
set3 = set([1,2,3,4,5])
set3
{1, 2, 3, 4, 5}
# 集合
set4 = set({1,2,3,4})
set4
{1, 2, 3, 4}
# 字典
set5 = set({'壹':1,2:2,3:'三'})
set5
{'壹', 3, 2}
3. 不可变集合frozenset()
- frozen:冰冻的
set5 = frozenset({1,2,3,4,5})
set5
frozenset({1, 2, 3, 4, 5})
set5.add(6)
报错:AttributeError: 'frozenset' object has no attribute 'add'
4. list与set的区别
list:
- 有序,可通过index访问
- 可重复
set
- 无序,不能通过index访问
- 元素唯一、不能重复
5. list列表去重
- 利用集合去重
- 转换成list类型
- 顺序发生变化
num = [1,1,2,2,3,3,4,4]
num2 = list(set(num))
num2
[1,2,3,4]
6. 判断集合中的值
5.1 in / not in
num = {1,2,3,4,5}
4 in num
True
9 in num
False