Python 常见优化技巧

1. 列表推导式 vs 循环

使用列表推导式能显著提升性能:

1
2
3
4
5
6
7
8
# 低效方式
result = []
for i in range(1000):
if i % 2 == 0:
result.append(i ** 2)

# 高效方式
result = [i ** 2 for i in range(1000) if i % 2 == 0]

2. 使用 defaultdict 简化代码

1
2
3
4
5
6
from collections import defaultdict

# 无需检查 key 是否存在
word_count = defaultdict(int)
for word in words:
word_count[word] += 1

3. 装饰器模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import functools
import time

def timing_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"耗时: {time.time() - start:.4f}s")
return result
return wrapper

@timing_decorator
def slow_function():
time.sleep(2)

4. 上下文管理器

1
2
3
4
5
6
7
8
9
10
class FileHandler:
def __enter__(self):
print("打开文件")
return self

def __exit__(self, *args):
print("关闭文件")

with FileHandler() as fh:
print("处理文件内容")

性能对比

方式 耗时 (ms) 备注
原始循环 15.2 基线
列表推导式 4.8 快 3 倍
生成器表达式 0.02 最快,并且节省内存

本文配置: Python 3.9+
难度: 中级
实用性: ⭐⭐⭐⭐⭐