Python 之 集合 set 的深入浅出
1、集合 set 概念
1.1 约定
- set 翻译为 集合
- collection 翻译为 集合类型,是一个大概念
1.2 set 性质
- 可变的
- 无序的
- 不重复的元素的集合
1.3 set 元素
-
set 的元素要求必须可以 hash
-
元素不可以使用索引
-
set 可以迭代
-
只要数据类型是可变的,均不可 hash,不可 hash 的类型有 list / set / dict / bytearray
-
可 hash 的数据类型:
1、数值型 int float complex 2、布尔型 True、False 3、字符串 string、bytes 4、元组 5、None 以上都是不可变类型,是可哈希类型, hashable
2、集合 set 的操作
2.1 set 定义 初始化
- 定义 set 时不能直接使用 {} 来定义
- {} 是定义字典使用的
- 定义 set 时只能使用 set() 函数来进行定义
set_a = set(range(5))
print(set_a, type(set_a))
set_b = set()
print(set_b, type(set_b))
set_c = set(list(range(5)))
print(set_c, type(set_c))
{
0, 1, 2, 3, 4} <class 'set'>
set() <class 'set'>
{
0, 1, 2, 3, 4} <class 'set'>
set_d = {
[1], 1, '1', (1,)}
print(set_c, type(set_c))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-0767f28c72b0> in <module>
----> 1 set_d = {
[1], 1, '1', (1,)}
2 print(set_c, type(set_c))
TypeError: unhashable type: 'list'
set_d = {
1, '1', (1,), {
1}}
print(set_c, type(set_c))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-e867ed634895> in <module>
----> 1 set_d = {
1, '1', (1,), {
1}}
2 print(set_c, type(set_c))
TypeError: unhashable type: 'set'
2.2 set 增加元素 add(elem)
- 增加一个元素到 set 中
- 如果元素存在,什么都不做
set_e = {
1, 2, 3}
print(1, set_e)
set_e.add(1)
print(2, set_e)
set_e.add(5)
print(3, set_e)
1 {
1, 2, 3}
2 {
1, 2, 3}
3