13.不知道这几个标准库,等于 Python 只用了一半
·
不知道这几个标准库,等于 Python 只用了一半
Python 有个说法叫"自带电池"(batteries included)——标准库里的东西非常多,很多需求不用装第三方包就能搞定。
今天挑几个最实用的讲。
collections:更好的数据结构
from collections import Counter, defaultdict, namedtuple, deque
# Counter:计数器
text = "hello world hello python"
word_count = Counter(text.split())
print(word_count) # Counter({'hello': 2, 'world': 1, 'python': 1})
print(word_count.most_common(2)) # [('hello', 2), ('world', 1)]
# 两个 Counter 还能加减
a = Counter("hello")
b = Counter("world")
print(a + b) # Counter({'l': 3, 'o': 2, ...})
# defaultdict:带默认值的字典
# 普通字典,键不存在就报错
d = {}
# d["count"] += 1 # KeyError!
# defaultdict,键不存在自动创建默认值
dd = defaultdict(int) # 默认值 0
dd["count"] += 1 # 没问题!
print(dd["count"]) # 1
dd2 = defaultdict(list) # 默认空列表
dd2["fruits"].append("苹果")
print(dd2) # {'fruits': ['苹果']}
# namedtuple:有名字的元组
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4,比 p[0] p[1] 可读性好太多了
# deque:双端队列,两头都快
dq = deque([1, 2, 3])
dq.appendleft(0) # 左边加
dq.append(4) # 右边加
dq.popleft() # 左边弹出
print(dq) # deque([1, 2, 3, 4])
datetime:别自己算日期
from datetime import datetime, timedelta, date
# 当前时间
now = datetime.now()
print(now) # 2026-06-23 16:30:00
# 格式化
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%Y年%m月%d日"))
# 解析
dt = datetime.strptime("2026-06-23", "%Y-%m-%d")
# 日期计算
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
three_hours_later = now + timedelta(hours=3)
# 两个日期相差几天
d1 = date(2026, 6, 1)
d2 = date(2026, 6, 23)
print((d2 - d1).days) # 22
timedelta 能加减的值:days, seconds, microseconds, milliseconds, minutes, hours, weeks。
random:随机数
import random
random.seed(42) # 固定随机种子,结果可复现
print(random.random()) # 0~1 之间的浮点数
print(random.randint(1, 10)) # 1~10 之间的整数
print(random.uniform(1.5, 3.5)) # 指定范围的浮点数
print(random.choice(["A", "B", "C"])) # 随机选一个
# 随机抽样
items = [1, 2, 3, 4, 5, 6, 7, 8]
print(random.sample(items, 3)) # 随机选3个,不重复
# 打乱列表(原地修改)
random.shuffle(items)
# 生成随机密码
import string
chars = string.ascii_letters + string.digits + "!@#$%"
password = "".join(random.choices(chars, k=12))
print(password)
re:正则表达式
import re
text = "我的邮箱是 zhangsan@example.com,电话是 138-0013-8000"
# 查找邮箱
email = re.search(r"[\w.]+@[\w.]+", text)
if email:
print(email.group()) # zhangsan@example.com
# 查找所有数字
numbers = re.findall(r"\d+", text)
print(numbers) # ['138', '0013', '8000']
# 替换
masked = re.sub(r"\d{3}-\d{4}-\d{4}", "***-****-****", text)
print(masked)
# 验证格式
def is_valid_phone(phone):
return bool(re.match(r"^1[3-9]\d{9}$", phone))
print(is_valid_phone("13800138000")) # True
print(is_valid_phone("12345")) # False
常用正则符号:
| 符号 | 含义 |
|---|---|
\d |
数字 |
\w |
字母数字下划线 |
\s |
空白字符 |
+ |
一个或多个 |
* |
零个或多个 |
? |
零个或一个 |
{n} |
恰好 n 个 |
{n,m} |
n 到 m 个 |
^ |
开头 |
$ |
结尾 |
os / sys / pathlib
import os
import sys
from pathlib import Path
# 系统信息
print(sys.platform) # win32 / darwin / linux
print(sys.version) # Python 版本
print(sys.argv) # 命令行参数
# 路径操作(推荐 pathlib)
cwd = Path.cwd()
home = Path.home()
print(cwd, home)
# 文件名操作
filepath = Path("/home/user/docs/report.pdf")
print(filepath.name) # report.pdf
print(filepath.stem) # report(无后缀)
print(filepath.suffix) # .pdf
print(filepath.parent) # /home/user/docs
# 遍历
for py_file in Path(".").glob("*.py"):
print(py_file.name)
# 创建目录
Path("new_dir/sub_dir").mkdir(parents=True, exist_ok=True)
argparse:命令行参数
import argparse
parser = argparse.ArgumentParser(description="文件处理工具")
parser.add_argument("input", help="输入文件路径")
parser.add_argument("-o", "--output", default="output.txt", help="输出文件")
parser.add_argument("-v", "--verbose", action="store_true", help="详细输出")
parser.add_argument("-n", "--count", type=int, default=1, help="处理次数")
args = parser.parse_args()
if args.verbose:
print(f"处理: {args.input} -> {args.output}")
print(f"次数: {args.count}")
# 运行: python script.py data.txt -o result.txt -v -n 5
一行代码搞定命令行参数解析。比手动解析 sys.argv 好一万倍。
itertools:迭代器工具
from itertools import chain, combinations, product, groupby
# 合并多个列表
for item in chain([1, 2], [3, 4], [5, 6]):
print(item) # 1 2 3 4 5 6
# 排列组合
for combo in combinations("ABC", 2):
print(combo) # ('A','B') ('A','C') ('B','C')
# 笛卡尔积
for pair in product("AB", [1, 2]):
print(pair) # ('A',1) ('A',2) ('B',1) ('B',2)
# 分组
data = [("A", 1), ("A", 2), ("B", 3), ("B", 4)]
for key, group in groupby(data, lambda x: x[0]):
print(key, list(group))
写在最后
标准库就像工具箱——你知道里面有什么,才能在想用的时候掏出来。
这几个库是我日常用得最多的:collections、datetime、pathlib、re、argparse。建议每个都打开 Python 敲一敲,光看是学不会的。
下一篇是最后一篇了——综合实战。把前面学的所有东西串起来,从零写一个命令行 Todo 应用。
更多推荐
所有评论(0)