1️⃣ 安装 & 全球统一暗号
# Windows/Mac/Linux 全适用
https://www.python.org/downloads/
# 国内镜像提速
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
import this # 彩蛋,Python 之道
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 tuple bytes
# 可变
list dict set bytearray
# 一行生成
lst = [1, 2, 3]
d = {'a': 1, 'b': 2}
t = (1, 2, 3) # 单元素 (1,)
s = {1, 2, 2} # 去重 {1, 2}
4️⃣ 函数式利器:lambda + 三件套🛠️
map(str, [1, 2, 3]) # 映射
filter(lambda x: x > 0, [-1, 0, 1]) # 过滤
reduce(lambda x, y: x + y, [1, 2, 3, 4]) # 累积
reduce在functools
5️⃣ 标准库“黄金 12 宫”⚡️
| 领域 | 模块 | 一行用途 |
|---|---|---|
| 文件 | os.path pathlib | 路径拼接/遍历 |
| 时间 | datetime | datetime.now().strftime('%Y-%m-%d') |
| 正则 | re | re.findall(r'\d+', text) |
| 并发 | concurrent.futures | ThreadPoolExecutor |
| 网络 | urllib | urllib.request.urlopen(url) |
| JSON | json | json.loads(str) |
| 配置 | argparse | 命令行参数 |
| 日志 | logging | logging.basicConfig(level=logging.INFO) |
| 压缩 | zipfile | 解压/压缩 |
| csv | csv | 读写表格 |
| 随机 | random secrets | 随机选/安全 token |
| 缓存 | functools.lru_cache | 函数结果缓存 |
6️⃣ 第三方神器:pip 一行安装🔥
pip install requests pandas numpy matplotlib seaborn
pip install flask fastapi scrapy pillow
7️⃣ Web 最快demo:Flask 5 行上线🌐
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello Python!"
app.run(debug=True) # http://127.0.0.1:5000
8️⃣ 爬虫最简:requests + BeautifulSoup🕷️
import requests, bs4, csv
url = "https://quotes.toscrape.com"
r = requests.get(url, timeout=10)
soup = bs4.BeautifulSoup(r.text, 'html.parser')
with open('quotes.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['quote', 'author'])
for q in soup.select('.quote'):
writer.writerow([q.text.strip(), q.small.text])
遵守 robots.txt,别猛冲🚀
9️⃣ 打包发布:pip install 你的代码📦
# 项目结构
mypkg/
├── mypkg/
│ └── __init__.py
├── setup.py
└── README.md
# setup.py 极简
from setuptools import setup
setup(name='mypkg', version='0.1', packages=['mypkg'])
python -m build
twine upload dist/*
🔟 性能黑魔法:加速 3 连招⚡️
| 技巧 | 代码 | 效果 |
|---|---|---|
| 向量化 | np.array(lst) * 2 | 比列表循环快 40× |
| 列表推导 | [f(x) for x in data] | 比 map+lambda 直观 |
| 并发 | concurrent.futures.ProcessPoolExecutor | CPU 密集并行 |
🏁 一句话口诀(背它!)
**“语法轻,库重兵,pip 装三方,Flask 跑 Web,pandas 做数据,并发提性能!”**🎖️