Python标准库精选:这些内置工具你一定要会

admin 📖 19 分钟阅读

1|# Python标准库精选:这些内置工具你一定要会 2| 3|## Python自带的武器库 4| 5|Python有"自带电池"(batteries included)的理念,标准库非常丰富。很多Java需要引入第三方库的功能,Python标准库就自带了。 6| 7|## 一、typing:Java程序员最需要的 8| 9|

    10|from typing import List, Dict, Optional, Union, Callable, Tuple, Any
    11|
    12|# 基础类型注解
    13|def greet(name: str) -> str:
    14|    return f"你好, {name}"
    15|
    16|# 复杂类型
    17|def process(data: List[Dict[str, Any]]) -> Optional[str]:
    18|    if not data:
    19|        return None
    20|    return data[0].get("name")
    21|
    22|# Python 3.10+ 联合类型(更简洁)
    23|def parse(value: str | int) -> float:
    24|    return float(value)
    25|
    26|# Python 3.12+ 泛型(更简洁)
    27|def first(items: list[T]) -> T:
    28|    return items[0]
    29|
    30|# Callable类型
    31|def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
    32|    return func(a, b)
    33|
34| 35|对比Java: 类型注解就是Java的泛型+注解,但Python是可选的。 36| 37|## 二、json:JSON处理 38| 39|
    40|import json
    41|
    42|data = {"name": "张三", "age": 25, "skills": ["Java", "Python"]}
    43|
    44|# 字典转JSON(ensure_ascii=False支持中文)
    45|json_str = json.dumps(data, ensure_ascii=False, indent=2)
    46|
    47|# JSON转字典
    48|parsed = json.loads(json_str)
    49|
    50|# 读写JSON文件
    51|with open("data.json", "w", encoding="utf-8") as f:
    52|    json.dump(data, f, ensure_ascii=False, indent=2)
    53|
    54|with open("data.json", "r", encoding="utf-8") as f:
    55|    loaded = json.load(f)
    56|
    57|# 自定义序列化
    58|class User:
    59|    def init(self, name, age):
    60|        self.name = name
    61|        self.age = age
    62|
    63|json_str = json.dumps(User("张三", 25), default=lambda o: o.dict)
    64|
65| 66|## 三、re:正则表达式 67| 68|
    69|import re
    70|
    71|# 搜索
    72|match = re.search(r"\d+", "abc123def")
    73|print(match.group())  # 123
    74|
    75|# 查找所有
    76|numbers = re.findall(r"\d+", "abc123def456")
    77|print(numbers)  # ['123', '456']
    78|
    79|# 替换
    80|text = re.sub(r"\d+", "*", "abc123def456")
    81|
    82|# 分组
    83|match = re.search(r"(\w+)@(\w+)\.com", "test@gmail.com")
    84|if match:
    85|    print(match.group(1))  # test
    86|
    87|# 编译(重复使用时更高效)
    88|pattern = re.compile(r"\b\w{5}\b")
    89|words = pattern.findall("hello world python java code")
    90|
    91|# flags
    92|re.IGNORECASE  # 忽略大小写
    93|re.MULTILINE   # 多行模式
    94|re.DOTALL      # .匹配换行符
    95|
96| 97|## 四、datetime:时间处理 98| 99|
   100|from datetime import datetime, timedelta, date, timezone
   101|import time
   102|
   103|# 当前时间
   104|now = datetime.now()
   105|utc_now = datetime.now(timezone.utc)
   106|
   107|# 格式化
   108|formatted = now.strftime("%Y-%m-%d %H:%M:%S")
   109|
   110|# 解析字符串
   111|parsed = datetime.strptime("2026-05-10", "%Y-%m-%d")
   112|
   113|# 时间运算
   114|tomorrow = now + timedelta(days=1)
   115|next_week = now + timedelta(weeks=1)
   116|
   117|# 差值
   118|delta = datetime(2026, 12, 31) - now
   119|print(f"距年底还有 {delta.days} 天")
   120|
   121|# 时间戳
   122|timestamp = now.timestamp()
   123|back = datetime.fromtimestamp(timestamp)
   124|
   125|# zoneinfo(Python 3.9+,替代pytz)
   126|from zoneinfo import ZoneInfo
   127|beijing_time = datetime.now(ZoneInfo("Asia/Shanghai"))
   128|
129| 130|## 五、collections:增强容器 131| 132|
   133|from collections import Counter, defaultdict, namedtuple, deque, ChainMap
   134|
   135|# Counter:计数器
   136|text = "hello world hello python"
   137|counter = Counter(text.split())
   138|print(counter.most_common(2))  # [('hello', 2), ('world', 1)]
   139|
   140|# defaultdict:带默认值的字典
   141|word_groups = defaultdict(list)
   142|for w in ["apple", "avocado", "banana"]:
   143|    word_groups[w[0]].append(w)
   144|
   145|# namedtuple:命名元组
   146|Point = namedtuple("Point", ["x", "y"])
   147|p = Point(10, 20)
   148|print(p.x, p.y)
   149|
   150|# deque:双端队列(两头O(1)操作)
   151|dq = deque([1, 2, 3])
   152|dq.appendleft(0)  # [0, 1, 2, 3]
   153|dq.pop()           # [0, 1, 2]
   154|dq.popleft()       # [1, 2]
   155|dq.rotate(1)       # [2, 1]
   156|
   157|# ChainMap:合并多个字典
   158|config = ChainMap({"debug": True}, {"host": "localhost"})
   159|print(config["debug"])  # True
   160|
161| 162|## 六、dataclasses:减少样板代码 163| 164|
   165|from dataclasses import dataclass, field
   166|
   167|# 基础用法(替代手写init/repr/eq)
   168|@dataclass
   169|class User:
   170|    name: str
   171|    age: int
   172|    email: str = ""  # 默认值
   173|
   174|user = User("张三", 25)  # 自动init
   175|print(user)  # User(name='张三', age=25, email='')
   176|print(user == User("张三", 25))  # True(自动eq)
   177|
   178|# frozen=True:不可变数据类
   179|@dataclass(frozen=True)
   180|class Point:
   181|    x: float
   182|    y: float
   183|
   184|p = Point(1, 2)
   185|# p.x = 3  # 报错!
   186|
   187|# field():高级配置
   188|@dataclass
   189|class Config:
   190|    name: str
   191|    tags: list = field(default_factory=list)  # 可变默认值
   192|    _internal: str = field(repr=False)        # 不显示在repr中
   193|    score: float = field(compare=False)       # 不参与比较
   194|
195| 196|## 七、pathlib:面向对象的路径操作 197| 198|
   199|from pathlib import Path
   200|
   201|# 创建路径
   202|p = Path("data") / "users" / "info.json"
   203|
   204|# 常用属性
   205|p = Path("/home/user/file.txt")
   206|print(p.name)      # file.txt
   207|print(p.stem)      # file
   208|print(p.suffix)    # .txt
   209|print(p.parent)    # /home/user
   210|
   211|# 读写文件(超简洁)
   212|text = p.read_text(encoding="utf-8")
   213|p.write_text("hello", encoding="utf-8")
   214|
   215|# 遍历
   216|for py_file in Path(".").glob("*/.py"):  # 递归查找
   217|    print(py_file)
   218|
   219|# 判断
   220|p.exists()
   221|p.is_file()
   222|p.is_dir()
   223|
224| 225|## 八、functools:函数式工具 226| 227|
   228|from functools import lru_cache, partial, reduce, wraps, total_ordering
   229|
   230|# lru_cache:记忆化
   231|@lru_cache(maxsize=128)
   232|def fibonacci(n):
   233|    if n < 2: return n
   234|    return fibonacci(n-1) + fibonacci(n-2)
   235|
   236|# partial:偏函数
   237|def power(base, exponent):
   238|    return base ** exponent
   239|
   240|square = partial(power, exponent=2)
   241|print(square(5))  # 25
   242|
   243|# reduce:累积
   244|from operator import add
   245|total = reduce(add, [1, 2, 3, 4, 5])  # 15
   246|
   247|# wraps:装饰器保留元信息
   248|def my_decorator(func):
   249|    @wraps(func)
   250|    def wrapper(*args, **kwargs):
   251|        return func(*args, **kwargs)
   252|    return wrapper
   253|
   254|# total_ordering:自动实现比较方法
   255|@total_ordering
   256|class Student:
   257|    def __init__(self, score):
   258|        self.score = score
   259|    def __eq__(self, other):
   260|        return self.score == other.score
   261|    def __lt__(self, other):
   262|        return self.score < other.score
   263|# 自动获得 <=, >, >=
   264|
265| 266|## 九、itertools:迭代器工具 267| 268|
   269|import itertools
   270|
   271|# product:笛卡尔积
   272|list(itertools.product([1,2], [3,4]))  # [(1,3),(1,4),(2,3),(2,4)]
   273|
   274|# combinations:组合
   275|list(itertools.combinations("ABCD", 2))  # AB,AC,AD,BC,BD,CD
   276|
   277|# permutations:排列
   278|list(itertools.permutations("ABC", 2))  # AB,AC,BA,BC,CA,CB
   279|
   280|# chain:链接迭代器
   281|list(itertools.chain([1,2], [3,4]))  # [1,2,3,4]
   282|
   283|# groupby:分组(需先排序)
   284|data = [("A",1),("A",2),("B",3),("B",4)]
   285|for key, group in itertools.groupby(data, lambda x: x[0]):
   286|    print(key, list(group))
   287|
   288|# islice:惰性切片
   289|list(itertools.islice(range(100), 10, 20))  # 10-19
   290|
   291|# tee:复制迭代器
   292|iter1, iter2 = itertools.tee(range(5))
   293|
   294|# accumulate:累积
   295|list(itertools.accumulate([1,2,3,4]))  # [1,3,6,10]
   296|
   297|# cycle:循环
   298|c = itertools.cycle([1,2,3])
   299|[next(c) for _ in range(7)]  # [1,2,3,1,2,3,1]
   300|
301| 302|## 十、其他重要标准库 303| 304|| 库 | 用途 | 示例 | 305||------|------|------| 306|| subprocess | 执行系统命令 | subprocess.run(["ls"], capture_output=True) | 307|| enum | 枚举 | class Color(Enum): RED=1; BLUE=2 | 308|| argparse | 命令行参数 | parser.add_argument("--name") | 309|| tempfile | 临时文件 | tempfile.NamedTemporaryFile() | 310|| shutil | 文件操作 | shutil.copy2(src, dst) | 311|| csv | CSV读写 | csv.DictReader(f) | 312|| sqlite3 | SQLite数据库 | with sqlite3.connect("db") as conn: | 313|| hashlib | 加密 | hashlib.sha256(data).hexdigest() | 314|| logging | 日志 | logging.getLogger(name) | 315|| unittest | 测试 | class TestXxx(TestCase): | 316|| http.server | 快速HTTP服务 | python -m http.server 8000 | 317|| zoneinfo | 时区 | ZoneInfo("Asia/Shanghai") | 318| 319|## 总结 320| 321|Python标准库的强大在于:你几乎不需要第三方库就能完成大部分工作。 322| 323|最后一篇:从Java到Python的思维转变和项目实战。 324| 325|--- 326| 327|本系列持续更新中,关注不迷路。

🤖 本文内容由AI辅助整理生成,仅供参考
← 上一篇 并发编程:多线程、协程和asyncio 下一篇 → 从Java到Python的思维转变:项目实战