Skip to content

Python 编程技巧

常用技巧

1. 列表推导式

python
# 基本用法
squares = [x**2 for x in range(10)]

# 带条件
evens = [x for x in range(10) if x % 2 == 0]

# 嵌套
matrix = [[i*j for j in range(3)] for i in range(3)]

2. 上下文管理器

python
# 使用 with 自动管理资源
with open('file.txt', 'r') as f:
    content = f.read()

# 自定义上下文管理器
from contextlib import contextmanager

@contextmanager
def timer():
    start = time.time()
    yield
    print(f"Time: {time.time() - start:.2f}s")

with timer():
    # 执行代码
    pass

3. 装饰器

python
from functools import wraps
import time

def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time() - start:.2f}s")
        return result
    return wrapper

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

4. 数据类

python
from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int
    email: str = ''

user = User(name='Allen', age=25)

性能优化

使用生成器

python
# 内存效率高
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# 使用
for num in fibonacci():
    if num > 1000:
        break
    print(num)

总结

Python 提供了丰富的语言特性,掌握这些技巧可以写出更优雅、高效的代码。