目录
2.4 OrderedDict - 有序字典(Python 3.7以后内置dict已经有序)
Python 标准库:常用功能模块详解与应用
Python 标准库包含了非常强大的模块,极大地方便了开发者日常编程任务。本文详细介绍并举例说明八大实用模块。
1. Base64 编码(base64
模块)
Base64 是将二进制数据编码为 ASCII 字符的方法,常用于网络传输、简单加密等。
基本编码与解码
Python
import base64
# 字节串编码
s = b'hello world'
encoded = base64.b64encode(s)
print(encoded) # 输出: b'aGVsbG8gd29ybGQ='
# 解码为字节串
decoded = base64.b64decode(encoded)
print(decoded) # 输出: b'hello world'
编码/解码字符串(注意需要编码为字节串)
Python
text = 'Python是好语言!'
encoded_text = base64.b64encode(text.encode('utf-8')) # 先转为字节串
print(encoded_text) # 输出: b'UHl0aG9u6KGo5aW977yM'
decoded_text = base64.b64decode(encoded_text).decode('utf-8')
print(decoded_text) # 输出: Python是好语言!
urlsafe 编解码(适用于url传输)
Python
data = b'abc+/'
encoded = base64.urlsafe_b64encode(data)
print(encoded) # b'YWJjKy8='
decoded = base64.urlsafe_b64decode(encoded)
print(decoded) # b'abc+/'
2. collections 容器数据类型
collections 扩展了内建数据类型,比如:namedtuple
、deque
、Counter
、OrderedDict
、defaultdict
、ChainMap
等。
2.1 namedtuple - 具名元组
Python
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(2, 3)
print(p.x, p.y) # 2 3
2.2 deque - 双端队列
Python
from collections import deque
dq = deque([1, 2, 3])
dq.append(4) # 右添加
dq.appendleft(0) # 左添加
print(dq) # deque([0, 1, 2, 3, 4])
dq.pop() # 输出:4
dq.popleft() # 输出:0
2.3 Counter - 计数器
Python
from collections import Counter
word = 'abracadabra'
counter = Counter(word)
print(counter) # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
# 取出最多的元素
print(counter.most_common(2)) # [('a', 5), ('b', 2)]
2.4 OrderedDict - 有序字典(Python 3.7以后内置dict已经有序)
Python
from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
for k, v in d.items():
print(k, v)
2.5 defaultdict - 带默认值字典
Python
from collections import defaultdict
dd = defaultdict(int)
dd['apple'] += 1
pr