本文目录导读:

基础语法与数据结构
斐波那契数列生成器(生成器与性能)
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 使用示例
list(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
知识点:生成器、yield、解包赋值
列表去重并保持顺序(散列与有序集合)
def dedup_ordered(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
# 使用示例
dedup_ordered([3, 1, 2, 1, 5, 3, 4]) # [3, 1, 2, 5, 4]
知识点:set的O(1)查找、保留原始顺序
词频统计(collections.Counter)
from collections import Counter
text = "hello world hello python world hello"
word_counts = Counter(text.split())
# Counter({'hello': 3, 'world': 2, 'python': 1})
# 出现最多的2个词
word_counts.most_common(2) # [('hello', 3), ('world', 2)]
知识点:Counter、most_common
实用工具与效率提升
进度条装饰器(函数式编程)
import time
from functools import wraps
def progress_bar(func):
@wraps(func)
def wrapper(*args, **kwargs):
total = len(args[0]) if args else 0
result = []
for i, item in enumerate(func(*args, **kwargs)):
# 模拟进度条
percent = (i + 1) / total * 100
print(f"\r处理中: {'█' * int(percent//4):25s} {percent:.1f}%", end='')
result.append(item)
print()
return result
return wrapper
@progress_bar
def process_items(items):
for item in items:
time.sleep(0.1) # 模拟耗时操作
yield item * 2
# 使用示例
processed = process_items(range(20))
知识点:装饰器、tqdm原理、yield from
配置文件热加载(动态模块重载)
import importlib
import time
class HotConfig:
def __init__(self, module_name='config'):
self.module_name = module_name
self.module = importlib.import_module(module_name)
def __getattr__(self, name):
# 每次访问都重新加载模块
importlib.reload(self.module)
return getattr(self.module, name)
# 假设有config.py: API_KEY = 'old_key'
# 修改config.py后,无需重启进程
config = HotConfig()
print(config.API_KEY) # 自动获取最新值
知识点:importlib.reload、元编程、getattr
数据科学常用
滑动窗口平均值(numpy加速)
import numpy as np
def moving_average(data, window_size):
if window_size <= 0:
raise ValueError("窗口大小必须为正")
cumsum = np.cumsum(np.insert(data, 0, 0))
return (cumsum[window_size:] - cumsum[:-window_size]) / window_size
# 使用示例
data = [1, 2, 3, 4, 5, 6, 7]
moving_average(data, 3) # array([2., 3., 4., 5., 6.])
知识点:cumsum、向量化运算、避免循环
One-Hot编码器(sklearn风格)
class OneHotEncoder:
def fit(self, data):
self.categories = sorted(set(data))
self.mapping = {cat: i for i, cat in enumerate(self.categories)}
def transform(self, data):
encoded = []
for item in data:
vec = [0] * len(self.categories)
vec[self.mapping[item]] = 1
encoded.append(vec)
return encoded
# 使用示例
encoder = OneHotEncoder()
encoder.fit(['cat', 'dog', 'bird', 'dog'])
encoder.transform(['bird', 'cat', 'dog']) # [[0,0,1], [1,0,0], [0,1,0]]
知识点:fit/transform范式、稀疏表示原理
网络与并发
异步爬虫框架(aiohttp)
import asyncio
import aiohttp
async def fetch(url, session):
async with session.get(url) as response:
return await response.text()
async def crawl(urls):
async with aiohttp.ClientSession() as session:
tasks = [fetch(url, session) for url in urls]
return await asyncio.gather(*tasks)
# 使用示例
urls = ['https://example.com', 'https://httpbin.org/get']
results = asyncio.run(crawl(urls))
知识点:asyncio、aiohttp、并发请求
生产者-消费者队列(threading)
import threading
import queue
import time
def producer(q, items):
for item in items:
print(f"生产 {item}")
q.put(item)
time.sleep(0.1)
q.put(None) # 哨兵值
def consumer(q):
while True:
item = q.get()
if item is None:
break
print(f"消费 {item}")
q.task_done()
# 使用示例
q = queue.Queue(maxsize=5)
t1 = threading.Thread(target=producer, args=(q, range(10)))
t2 = threading.Thread(target=consumer, args=(q,))
t1.start(); t2.start()
t1.join(); t2.join()
知识点:Queue、线程同步、哨兵模式
趣味与实战
表情包生成器(PIL图像处理)
from PIL import Image, ImageDraw, ImageFont
def add_text_to_image(image_path, text, output_path):
img = Image.open(image_path)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("simhei.ttf", 40)
# 在图片底部添加文字(带白色底框)
bbox = draw.textbbox((0, 0), text, font=font)
text_w = bbox[2] - bbox[0]
text_h = bbox[3] - bbox[1]
x = (img.width - text_w) // 2
y = img.height - text_h - 20
draw.rectangle([x-10, y-10, x+text_w+10, y+text_h+10], fill='white')
draw.text((x, y), text, fill='black', font=font)
img.save(output_path)
# 使用示例
add_text_to_image('meme.jpg', '我全都要', 'meme_with_text.jpg')
知识点:PIL、中文字体渲染、矩形遮罩
系统托盘通知(跨平台)
from plyer import notification
def show_notification(title, message, timeout=5):
notification.notify(
title=title,
message=message,
app_name='Python小助手',
timeout=timeout
)
# 使用示例
show_notification('提醒', '程序运行完毕!', 10)
知识点:plyer库、跨平台通知
面试经典
判断括号是否有效(栈应用)
def is_valid_brackets(s):
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in mapping:
if not stack or stack[-1] != mapping[char]:
return False
stack.pop()
else:
stack.append(char)
return len(stack) == 0
# 测试
is_valid_brackets("()[]{}") # True
is_valid_brackets("([)]") # False
知识点:栈、哈希映射、边界条件
LRU缓存(有序字典)
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
elif len(self.cache) >= self.capacity:
self.cache.popitem(last=False) # 移除最早访问的
self.cache[key] = value
# 使用示例
cache = LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
cache.get(1) # 返回 1
cache.put(3, 3) # 淘汰 key 2
cache.get(2) # 返回 -1
知识点:OrderedDict、move_to_end、popitem
推荐学习路径:
- 初学者:重点掌握#1、#2、#6、#12
- 进阶:学习#5、#8、#13
- 工程实践:理解#4、#9、#11的设计模式
这些案例涵盖了Python的80%核心特性,建议你动手运行代码,尝试修改参数看效果变化,需要某个案例的详细解释吗?