
1️⃣ 安装 & 全球统一暗号
python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -U pip
import this
2️⃣ 语法速写:一张表背完📜
| 关键字 | 场景 | 一行示例 |
|---|
if | 条件 | x if x > 0 else 0 |
for | 循环 | [i*2 for i in range(5)] |
while | 条件循环 | while line := f.readline(): |
try | 异常 | try/except/finally |
with | 上下文 | with open('f') as f: 自动关 |
def | 函数 | def add(a, b=1): return a + b |
class | 类 | class Dog: def __init__(self): pass |
import | 模块 | import pandas as pd |
3️⃣ 超常用数据类型:8 个走天下🌟
int float bool str list tuple dict set
lst = [1, 2, 3]
d = {'a': 1, 'b': 2}
t = (1, 2, 3)
s = {1, 2, 2}
4️⃣ 万能模板:控制台输入 + 集合 + 排序💡
import sys, random
n = int(sys.stdin.readline())
lst = [random.randint(0, 100) for _ in range(n)]
lst.sort(reverse=True)
print(*lst)
5️⃣ 文件读写:一行复制🖊️
txt = open('a.txt', encoding='utf-8').read()
open('b.txt', 'w', encoding='utf-8').write(txt.upper())
6️⃣ 网络请求:内置 urllib✈️
import urllib.request, json
url = "https://api.github.com/users"
body = urllib.request.urlopen(url).read()
print(json.loads(body)[:3])
7️⃣ 并发加速:线程池一把梭⚙️
from concurrent.futures import ThreadPoolExecutor as Pool
with Pool() as p:
results = p.map(str.upper, ['a', 'b', 'c'])
print(list(results))
8️⃣ 打包发布:pip install 你的代码📦
mypkg/
├── mypkg/
│ └── __init__.py
└── pyproject.toml
[project]
name = "mypkg"
version = "0.1.0"
dependencies = []
python -m pip install build
python -m build
twine upload dist/*
9️⃣ 性能黑魔法:加速 3 连招⚡️
| 技巧 | 代码 | 效果 |
|---|
| 向量化 | np.array(lst) * 2 | 比列表循环快 40× |
| 列表推导 | [f(x) for x in data] | 比 map+lambda 直观 |
| 并发 | concurrent.futures.ProcessPoolExecutor | CPU 密集并行 |
🔟 常用第三方库:pip 一行安装✅
pip install requests pandas numpy matplotlib seaborn
pip install flask fastapi scrapy pillow