速查 11 · Python
按问题索引。Ctrl+F 页内搜索。 系统学习(与 TS/Dart 对照、迁移陷阱)见 01 · Python 语言基础与 TS 对照。
主要服务场景:FastAPI 后端 + AI/脚本。Python 用缩进定作用域,注意没有
{ }。
目录
环境与依赖管理
bash
python -m venv .venv # 建虚拟环境(≈ npm 的 node_modules 隔离)
source .venv/bin/activate # 进入(Windows PowerShell: .venv\Scripts\Activate.ps1)
pip install -r requirements.txt # 装依赖(≈ npm install)
pip freeze > requirements.txt # 导出依赖锁(≈ package-lock)
pip list # 看已装
deactivate # 退出虚拟环境Windows 下
python可能指向微软商店占位程序,优先用py -3.12或显式版本。
常用数据结构
python
# list 列表(≈ 数组,可存不同类型)
nums = [1, 2, 3]
nums.append(4) # 末尾追加
nums[0], nums[-1] # 首元素、末元素(负数索引!)
nums[1:3] # 切片 [1,2) → [2, 3]
# dict 字典(≈ Map / 对象)
user = {"name": "sunqy", "age": 18}
user["name"] # 读,键不存在抛 KeyError
user.get("email", "none") # 安全读,带默认值
user["age"] = 19 # 写
# set 集合(去重)
tags = {"a", "b", "a"} # {"a", "b"}
tags.add("c")
# tuple 元组(不可变)
point = (1, 2)
x, y = point # 解构列表推导式与常用操作
python
# 列表推导式(≈ map + filter 的合体)
squares = [x * x for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64]
# 字典推导式
square_map = {x: x * x for x in range(5)}
# 常用内置函数
len(xs) # 长度
sorted(xs, key=lambda x: x["age"], reverse=True) # 排序(不修改原数组)
sum(xs), max(xs), min(xs)
enumerate(xs) # 带下标迭代 → (0, item), (1, item)...
zip(a, b) # 并行迭代两个列表
any(...), all(...)
# 过滤 / 映射(比推导式更函数式)
evens = list(filter(lambda x: x % 2 == 0, xs))
names = list(map(lambda u: u["name"], users))
# 字符串拼接(不要用 + 循环)
joined = ", ".join(["a", "b", "c"]) # "a, b, c"字符串 / 日期 / 文件
python
text = " hello world "
text.strip() # "hello world"
text.upper(), text.lower()
text.replace("world", "python")
text.split(",") # 按分隔符拆列表
parts = ["a", "b"]; ",".join(parts)
text.startswith("he"), text.endswith("d")
len(text), text[0:5]
# 字符串格式化(推荐 f-string,Python 3.6+)
name = "sunqy"
msg = f"Hello, {name}! {2 + 3}"
# 日期
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
now.isoformat() # "2026-10-13T09:30:00+00:00"
datetime.fromisoformat("2026-10-13T09:30:00") # 解析
# 文件读写(with 自动关闭)
with open("data.json", "r", encoding="utf-8") as f:
content = f.read()
with open("out.txt", "w", encoding="utf-8") as f:
f.write("hello")
# 读取大文件按行(不一次加载全量)
with open("big.log", encoding="utf-8") as f:
for line in f:
print(line.strip())函数与异常
python
def greet(name, prefix="Hi", *, strict=False):
"""函数文档字符串(docstring)"""
if strict and not name:
raise ValueError("name 不能为空")
return f"{prefix}, {name}"
# *args 变长位置参数 / **kwargs 变长关键字
def log(*args, **kwargs):
print(args, kwargs)
# lambda 匿名函数(≈ 箭头函数)
add = lambda a, b: a + b
# 异常处理:try/except/finally(≈ try/catch/finally)
try:
result = risky()
except ValueError as e: # 精确捕获
print("值错误:", e)
except (TypeError, KeyError):
print("类型或键错误")
else:
print("无异常才执行")
finally:
cleanup() # 无论是否异常都执行
# 注意:Python 异常开销高,别用异常做正常流程控制类型注解
python
from typing import Optional, Union, List, Dict, Any
# 注意:注解只做提示,运行时**不校验**(要校验用 pydantic)
def add(a: int, b: int) -> int:
return a + b
def find(users: List[Dict[str, Any]], key: str) -> Optional[Dict[str, Any]]:
...
# 3.10+ 用 | 替代 Union
def f(x: str | None) -> str | None:
return x
# 联合 / 字面量(配合 Literal)
from typing import Literal
Status = Literal["idle", "loading", "done"]
# dataclass ≈ 轻量 DTO
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
email: str = "" # 默认值
u = User(1, "sunqy")JSON 与网络请求
python
import json
# 序列化 / 反序列化
data = {"a": 1, "b": [1, 2]}
text = json.dumps(data, ensure_ascii=False) # 中文不转义
parsed = json.loads(text)
# 读 JSON 文件
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
# HTTP 请求(requests,第三方但事实标准)
import requests
resp = requests.get("https://api.example.com/users", timeout=10)
resp.raise_for_status() # 非 2xx 抛异常
users = resp.json()
resp = requests.post(
"https://api.example.com/users",
json={"name": "sunqy"}, # json= 自动设 Content-Type 并序列化
headers={"Authorization": "Bearer xxx"},
timeout=10,
)异步 asyncio
python
import asyncio
async def fetch(url: str) -> str:
# await 之前先"让出",才能并发
await asyncio.sleep(1) # 模拟网络 IO
return url
async def main():
# 并发跑三个任务(≈ Promise.all)
results = await asyncio.gather(
fetch("a"), fetch("b"), fetch("c")
)
return results
# 入口:asyncio.run 只调用一次
out = asyncio.run(main())
# 注意:asyncio 是"单线程协作式"并发,不是多线程并行;
# 阻塞型 IO(requests、同步 sleep)会卡住整个事件循环,要走线程池路径与系统
python
from pathlib import Path
root = Path(__file__).resolve().parent # 当前文件所在目录(跨平台!)
data_path = root / "data" / "input.json" # 用 / 拼路径,别用字符串 +
data_path.exists() # 是否存在
data_path.read_text(encoding="utf-8") # 读文本
data_path.write_text("hi", encoding="utf-8")
for f in root.glob("*.json"): # 通配符遍历
print(f.name, f.stat().st_size)
# 环境变量(.env 由 pydantic-settings / python-dotenv 读取)
import os
secret = os.environ.get("API_KEY", "")
if not secret:
raise RuntimeError("缺少 API_KEY")常见报错速查
| 报错 | 原因 / 解法 |
|---|---|
ModuleNotFoundError: No module named 'x' | 没装依赖或虚拟环境没激活:pip install x |
KeyError: 'x' | dict 键不存在:用 get 或先判 in |
IndexError: list index out of range | 下标越界:负数索引或 if xs: 判空 |
TypeError: 'NoneType' object is not subscriptable | 返回了 None 还当对象用:先判空 |
IndentationError | 缩进不一致,Python 靠缩进分层级 |
UnicodeDecodeError | 文件编码不是 utf-8,open(..., encoding=...) 显式指定 |
AttributeError: 'str' object has no attribute 'append' | 类型用错方法,确认是 list/dict 再调 |
RuntimeWarning: coroutine 'x' was never awaited | async 函数忘加 await |