这是我参与11月更文挑战的8天,活动详情查看:2021最后一次更文挑战。
Bytes
在Python3
以后,字符串和bytes
类型彻底分开了:
字符串
是以字符
为单位进行处理的。bytes
类型是以字节
为单位处理的。
bytes
数据类型在所有的操作和使用甚至内置方法上和字符串数据类型基本一样,也是不可变的序列对象。
调用bytes()
生成bytes
实例。对于同一个字符串如果采用不同的编码方式生成bytes
对象,就会形成不同的值:
>>> a = b'hello'
>>> type(a)
<class 'bytes'>
>>> b = bytes('hello',encoding='utf8')
>>> type(b)
<class 'bytes'>
复制代码
bytes
类型常用转换
- 字节转成字符串
>>> d = b'world'
>>> d.decode()
'world'
>>> type(d)
<class 'bytes'>
复制代码
- 字符串转为字节
>>> e = 'world'
>>> e.encode()
b'world'
>>> type(e)
<class 'str'>
复制代码
集合set
set集合
:无序不重复元素的集合,基本功能包括:
- 关系测试
- 消除重复元素
set
使用大括号{}
框定元素,并以逗号进行分隔: ⚠️注意:如果要创建一个空集合,必须用 set()
而不是 {}
,因为后者创建的是一个空字典。
>>> s = {1,2,3}
>>> s
{1, 2, 3}
>>> type(s)
<class 'set'>
>>> s = {} # 注意,空的{}会默认为字典
>>> type(s)
<class 'dict'>
>>> s = set() # 创建空集合->new empty set object(创建空集合)
>>> s
set()
>>> type(s)
<class 'set'>
>>> s = set([1,2,3,1,2,3,4]) # 创建集合,去重
>>> s
{1, 2, 3, 4}
>>> s1 = set("hello world") # 创建集合,去重
>>> s1
{'h', 'd', 'o', ' ', 'e', 'l', 'r', 'w'}
>>> s2 = set(123) # 注意,需要传入可迭代的对象,而int类型的123并不是,所以报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
复制代码
集合添加元素
通过add(key)
方法可以添加元素到set
中,可以重复添加,但不会有效果:
>>> s = set([1,2,3,1,2,3,4])
>>> s
{1, 2, 3, 4}
>>> s.add(3) # 重复添加,自动去重
>>> s
{1, 2, 3, 4}
>>> s.add(6) # 添加成功
>>> s
{1, 2, 3, 4, 6}
>>> s.add("cat") # 添加成功
>>> s
{1, 2, 3, 4, 6, 'cat'}
>>> s.add([1,2,3]) # 报错,同字典一样 不能添加可变对象
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
复制代码
集合更新
可以通过update()
方法,将另一个对象更新到已有的集合中,这一过程同样会进行去重:
>>> s = set([1,2,3,4,5])
>>> s.update("hello") # 将hello拆开放入集合
>>> s
{1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}
>>> s.update("hello") # 仍然去重
>>> s
{1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}
复制代码
删除元素
通过remove(key)
方法删除指定元素,或者使用pop()
方法。注意,集合的pop
方法无法设置参数,删除指定的元素:
set.remove()
>>> s = {1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}
>>> s.remove(1) # 删除该元素
>>> s
{2, 3, 4, 5, 'h', 'o', 'e', 'l'}
>>> s.remove('h') # 删除该元素
>>> s
{2, 3, 4, 5, 'o', 'e', 'l'}
>>> s.remove('www') # 删除不存在的元素则报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'www'
复制代码
set.pop()
>>> s1 = set("hello world")
>>> s1.pop()
'h'
>>> s1.pop()
'd'
>>> s1.pop() # 注意是随机删除
'o'
>>> s1.pop(1) # 不能通过索引删除,因为本身无序
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop() takes no arguments (1 given)
复制代码
⚠️注意:集合不能取出某个元素,因为集合既不支持下标索引也不支持字典那样的通过键值对获取:
>>> s1
{' ', 'e', 'l', 'r', 'w'}
>>> s1[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
复制代码