首页 / 速查手册 / 在线

Python速查手册

Python语法/标准库/环境管理速查表

速查手册 · 1 次 · 2026-10-04 · 分享 · 全屏

🐍 基础语法

变量与类型

动态强类型,无需声明;type() 查看类型,isinstance() 判断类型。

n = 10            # int
s = "hello"       # str
f = 3.14          # float
b = True          # bool
print(type(n))          # <class 'int'>
print(isinstance(n, int))  # True
f-string 格式化

推荐的字符串插值方式,支持表达式、精度与对齐。

name, age = "Tom", 18
print(f"{name} 今年 {age} 岁")
print(f"{3.14159:.2f}")        # 3.14
print(f"{'左':<6}{'右':>6}")   # 对齐填充
print(f"{1000000:,}")          # 1,000,000
输入 input

input() 永远返回字符串,数字需自行转换。

name = input("请输入姓名:")
age = int(input("请输入年龄:"))
nums = list(map(int, input("空格分隔:").split()))
条件判断

靠缩进表示代码块,注意 elif 拼写。

score = 75
if score >= 90:
    print("优")
elif score >= 60:
    print("及格")
else:
    print("不及格")

# 三元表达式
level = "成年" if age >= 18 else "未成年"
循环 for / while

for 直接遍历可迭代对象;range 控制次数;break/continue 通用。

for i in range(5):        # 0 1 2 3 4
    print(i, end=" ")
for i in range(2, 10, 2): # 2 4 6 8
    print(i)

while n > 0:
    n -= 1
    if n == 3:
        continue
定义函数

支持默认参数、可变参数 *args、关键字参数 **kwargs。

def greet(name, greeting="你好", *args, **kwargs):
    """文档字符串:say hello"""
    return f"{greeting}, {name} {args} {kwargs}"

print(greet("Tom"))
print(greet("Amy", "嗨", 1, 2, x=3))
异常捕获

try/except/else/finally,可手动 raise。

try:
    n = int("abc")
except ValueError as e:
    print("转换失败:", e)
except (TypeError, KeyError):
    print("其他异常")
else:
    print("无异常时执行")
finally:
    print("总会执行")

raise ValueError("参数非法")
enumerate 与 zip

遍历时同时拿索引/值;zip 并行遍历多个序列。

for i, ch in enumerate(["a", "b", "b"], start=1):
    print(i, ch)            # 1 a / 2 b / 3 b

names, ages = ["Tom", "Amy"], [18, 20]
for name, age in zip(names, ages):
    print(name, age)

print(dict(zip(names, ages)))   # {'Tom': 18, 'Amy': 20}

📦 数据结构

列表 list

可变有序序列,最常用的数据容器。

a = [1, 2, 3]
a.append(4)          # 末尾加一个
a.extend([5, 6])     # 批量追加
a.insert(0, 0)       # 指定位置插入
a.pop()              # 弹出末尾
a.remove(2)          # 删除第一个值为 2 的元素
a.sort(reverse=True) # 原地排序
print(sorted(a))     # 返回新列表,不改原列表
切片 [start:stop:step]

字符串、列表、元组通用,左闭右开。

a = [0, 1, 2, 3, 4, 5]
a[1:4]     # [1, 2, 3]
a[:3]      # [0, 1, 2]
a[3:]      # [3, 4, 5]
a[::2]     # [0, 2, 4]  步长 2
a[::-1]    # [5, 4, 3, 2, 1, 0] 反转
b = a[:]   # 浅拷贝一份
元组与序列解包

元组不可变;* 接收剩余元素;交换变量无需中间量。

point = (3, 4)
x, y = point
a, *rest = [1, 2, 3, 4]   # a=1, rest=[2,3,4]
first, *mid, last = [1, 2, 3, 4]

a, b = b, a               # 快速交换
def divmod2(n, d):
    return n // d, n % d  # 多返回值就是元组
字典 dict

键值对;get 可给默认值,遍历用 items()。

d = {"a": 1, "b": 2}
d["c"] = 3
print(d.get("x", 0))        # 键不存在返回 0,不报错
d.update({"b": 20, "d": 4})
d.setdefault("list", []).append(1)

for k, v in d.items():
    print(k, v)
print(list(d.keys()), list(d.values()))
d.pop("a")                  # 删除键
集合 set

无序不重复,适合去重和集合运算。

s = {1, 2, 3}
s.add(4); s.discard(99)   # 删除不存在也不报错
a, b = {1, 2, 3}, {2, 3, 4}
a & b      # {2, 3}       交集
a | b      # {1,2,3,4}    并集
a - b      # {1}          差集
a ^ b      # {1, 4}       对称差

print(list(set([1, 1, 2, 3, 3])))   # 去重 [1,2,3]
自定义排序 sorted

key 指定排序依据,可多关键字。

users = [{"name": "Tom", "age": 30},
         {"name": "Amy", "age": 18}]
sorted(users, key=lambda u: u["age"])
sorted(users, key=lambda u: (-u["age"], u["name"]))

words = ["banana", "fig", "apple"]
print(sorted(words, key=len))             # 按长度
print(sorted(words, key=str.lower, reverse=True))
字符串常用方法

字符串不可变,所有方法都返回新字符串。

"  hi  ".strip()            # "hi"
"a,b,c".split(",")          # ['a','b','c']
"-".join(["a", "b", "c"])   # "a-b-c"
"hello".replace("l", "L")   # "heLLo"
"Hello".lower() / "x".upper()
"demo.py".endswith(".py")
"hi {}".format("Tom")
", ".join(map(str, [1, 2, 3]))   # "1, 2, 3"

🧮 推导式

列表推导式

用一行表达 map/filter,Python 最常用语法糖。

[x * x for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
带过滤条件

if 写在后面做过滤;也可在前面做分支。

[x for x in range(20) if x % 2 == 0]
# [0, 2, 4 ... 18]

[x if x % 2 == 0 else -x for x in range(6)]
# [0, -1, 2, -3, 4, -5]
字典与集合推导式

换成 {} 并以 key: value 形式书写。

{k: len(k) for k in ["a", "bb", "ccc"]}
# {'a': 1, 'bb': 2, 'ccc': 3}

{v: v * v for v in range(4)}
{c for c in "hello"}              # 集合:{'h','e','l','o'}
{k: v for k, v in d.items() if v > 0}
多层嵌套推导

for 顺序与普通嵌套循环完全一致。

[(x, y) for x in range(3) for y in range(3)]
# [(0,0),(0,1),(0,2),(1,0),...]

matrix = [[1, 2], [3, 4]]
flat = [n for row in matrix for n in row]
# [1, 2, 3, 4]

📁 文件读写

with 读取整个文件

with 自动关闭文件;务必指定 encoding 避免平台默认编码坑。

with open("a.txt", encoding="utf-8") as f:
    text = f.read()
print(text)
按行读取

直接遍历文件对象最省内存;strip() 去掉换行符。

with open("a.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip("\n"))

# 需要行号时
with open("a.txt", encoding="utf-8") as f:
    rows = [line.strip() for line in f if line.strip()]
写文件与打开模式

w 覆盖写、a 追加、r 读;加 b 为二进制模式。

with open("b.txt", "w", encoding="utf-8") as f:
    f.write("第一行\n")
    f.writelines(["第二行\n", "第三行\n"])

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("追加一条\n")

with open("img.png", "rb") as f:   # 二进制读
    data = f.read()
读写 JSON

ensure_ascii=False 保留中文,indent 美化输出。

import json

obj = {"name": "张三", "tags": ["a", "b"]}
with open("u.json", "w", encoding="utf-8") as f:
    json.dump(obj, f, ensure_ascii=False, indent=2)

with open("u.json", encoding="utf-8") as f:
    data = json.load(f)

json.dumps(obj, ensure_ascii=False)   # 转字符串
json.loads('{"a": 1}')                # 字符串解析
读写 CSV

DictReader/DictWriter 按表头映射为字典。

import csv

with open("users.csv", encoding="utf-8-sig", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["age"])

with open("out.csv", "w", encoding="utf-8-sig", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["name", "age"])
    w.writeheader()
    w.writerow({"name": "Tom", "age": 18})

🛠 os / sys / subprocess

os 路径与目录

os.path 拼路径,递归建目录用 makedirs。

import os

os.getcwd()                         # 当前工作目录
os.listdir(".")                     # 列目录
os.makedirs("a/b/c", exist_ok=True) # 递归创建
p = os.path.join("dir", "a.txt")    # 跨平台拼路径
os.path.exists(p)                   # 是否存在
os.path.isdir(p) / os.path.isfile(p)
os.path.basename(p) / os.path.splitext(p)
os.remove("f.txt")                  # 删文件
os.rmdir("empty_dir")               # 删空目录
sys 命令行参数

argv[0] 是脚本本身;也可查看平台与退出码。

import sys

print(sys.argv)        # python app.py 8080 -> ['app.py','8080']
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
print(sys.platform)    # win32 / linux / darwin
print(sys.version)     # Python 版本
sys.exit(1)            # 退出脚本,0 成功非 0 失败
环境变量

子进程会继承当前进程设置的环境变量。

import os

os.environ.get("PATH", "")
os.environ.get("NODE_ENV", "development")
os.environ["MY_TOKEN"] = "secret"   # 仅当前进程有效
os.putenv?  # 推荐统一用 os.environ 赋值
执行外部命令 subprocess

优先列表形式参数避免 shell 注入;check=True 非零退出抛异常。

import subprocess

r = subprocess.run(["python", "--version"],
                   capture_output=True, text=True)
print(r.returncode, r.stdout, r.stderr)

subprocess.run(["ls", "-l"], check=True)   # 失败抛异常
out = subprocess.check_output(["echo", "hi"], text=True)
subprocess.run("echo $HOME", shell=True)   # 需要 shell 特性时

📅 json 与 datetime

json 字符串互转

dumps/loads 操作字符串,dump/load 操作文件。

import json

s = json.dumps({"a": 1, "b": [1, 2]}, ensure_ascii=False)
d = json.loads(s)

# 美化 + 键排序
json.dumps(d, indent=2, sort_keys=True, ensure_ascii=False)
datetime 取当前时间与格式化

strftime 转字符串,strptime 字符串转时间。

from datetime import datetime

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.year, now.month, now.day, now.weekday())

d = datetime.strptime("2026-10-04", "%Y-%m-%d")
print(d.isoformat())       # 2026-10-04T00:00:00
日期加减 timedelta

时间差支持天/秒/微秒;日期相减得到 timedelta。

from datetime import datetime, timedelta

now = datetime.now()
now + timedelta(days=7)          # 7 天后
now - timedelta(hours=2)         # 2 小时前
now + timedelta(weeks=2, hours=3)

deadline = datetime(2026, 12, 31)
left = deadline - now
print(left.days, left.total_seconds())

🧰 collections 与 itertools

Counter 计数

一键统计频次,most_common 取 Top N。

from collections import Counter

c = Counter("aabbbc")
print(c)                 # Counter({'b':3,'a':2,'c':1})
print(c.most_common(2))  # [('b',3),('a',2)]

c2 = Counter(["red", "blue", "red"])
c + Counter({"red": 5})  # 计数器可加减
defaultdict 与 deque

defaultdict 自动初始化缺失键;deque 高效双端队列。

from collections import defaultdict, deque

groups = defaultdict(list)
for word in ["apple", "ant", "bee"]:
    groups[word[0]].append(word)
# {'a': ['apple','ant'], 'b': ['bee']}

q = deque([1, 2], maxlen=5)
q.append(3); q.appendleft(0)
q.pop(); q.popleft()
itertools 迭代器工具

分组、笛卡尔积、排列组合、扁平化。

from itertools import chain, groupby, product, combinations

list(chain.from_iterable([[1, 2], [3, 4]]))  # [1,2,3,4]
list(product("ab", [1, 2]))   # [('a',1),('a',2),('b',1),('b',2)]
list(combinations("abc", 2))  # [('a','b'),('a','c'),('b','c')]

for k, g in groupby(sorted(["a1","a2","b1"]), key=lambda s: s[0]):
    print(k, list(g))         # a ['a1','a2'] / b ['b1']

🌿 pathlib 面向对象路径

拼接与属性

用 / 运算符拼路径,跨平台自动处理分隔符。

from pathlib import Path

p = Path(".") / "assets" / "img" / "a.png"
p.exists()
p.is_file() / p.is_dir()
p.name           # 'a.png'
p.stem           # 'a'
p.suffix         # '.png'
p.parent         # assets/img
p.resolve()      # 绝对路径
便捷读写

read_text/write_text 一行搞定小文件。

from pathlib import Path

Path("note.txt").write_text("你好", encoding="utf-8")
text = Path("note.txt").read_text(encoding="utf-8")
data = Path("a.bin").read_bytes()

p = Path("dir")
p.mkdir(parents=True, exist_ok=True)
p.joinpath("sub", "f.txt").unlink(missing_ok=True)
glob 查找文件

** 表示任意层级子目录。

from pathlib import Path

list(Path(".").glob("*.py"))          # 当前目录 .py
list(Path(".").rglob("*.py"))         # 递归,同 glob("**/*.py")
list(Path("src").glob("**/*.json"))

for f in Path(".").glob("*.log"):
    print(f.stat().st_size, f)        # 文件大小

📲 虚拟环境与 pip

创建并激活虚拟环境

项目依赖隔离,venv 是标准库自带方案。

python -m venv .venv

# macOS / Linux
source .venv/bin/activate

# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# Windows (cmd)
.venv\Scripts\activate.bat

deactivate          # 退出虚拟环境
安装依赖

-r 按清单安装;可指定版本范围。

pip install requests
pip install "django>=4.2,<5.0"
pip install -r requirements.txt
pip install --upgrade pip
python -m pip install flask    # 防止装到错误的解释器环境
导出 / 查看 / 卸载

freeze 锁定精确版本,便于复现环境。

pip freeze > requirements.txt
pip list                 # 已装包列表
pip show requests        # 查看包详情
pip uninstall -y requests
pip check                # 检查依赖冲突
国内镜像加速

临时用 -i 指定,长期建议写入全局配置。

# 临时使用清华镜像
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

# 永久设置默认镜像
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

# requirements 中也可加注释:
# --index-url https://pypi.tuna.tsinghua.edu.cn/simple

📖 使用说明

全程在浏览器本地运行。

操作步骤:

  1. 搜索或浏览分类条目;
  2. 查看语法与示例代码;
  3. 点击复制代码块。

💬 用户评论 (0)

还没有评论,快来抢沙发!

请添加微信联系我