Python 超能速通包

0 阅读2分钟

微信图片_20251014151033_10_20.jpg

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
classclass 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])  # 累积

reducefunctools


5️⃣ 标准库“黄金 12 宫”⚡️

领域模块一行用途
文件os.path pathlib路径拼接/遍历
时间datetimedatetime.now().strftime('%Y-%m-%d')
正则rere.findall(r'\d+', text)
并发concurrent.futuresThreadPoolExecutor
网络urlliburllib.request.urlopen(url)
JSONjsonjson.loads(str)
配置argparse命令行参数
日志logginglogging.basicConfig(level=logging.INFO)
压缩zipfile解压/压缩
csvcsv读写表格
随机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.ProcessPoolExecutorCPU 密集并行

🏁 一句话口诀(背它!)

**“语法轻,库重兵,pip 装三方,Flask 跑 Web,pandas 做数据,并发提性能!”**🎖️