Python 编程小技巧
·
这里为您总结一些实用且地道的 Python 编程技巧,从基础到进阶。
🎯 基础必备技巧
- 多重赋值与序列解包
# 传统方式
a = 1
b = 2
c = 3
# Pythonic 方式
a, b, c = 1, 2, 3
# 交换变量值
a, b = b, a # 不需要临时变量
# 解包列表/元组
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
- 列表推导式 (List Comprehensions)
# 传统方式
squares = []
for x in range(10):
squares.append(x**2)
# Pythonic 方式
squares = [x**2 for x in range(10)]
# 带条件的推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# 嵌套循环
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6]
- 字典与集合推导式
# 字典推导式
square_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 交换键值对
inverted = {v: k for k, v in square_dict.items()}
# 集合推导式
unique_squares = {x**2 for x in [1, 2, 2, 3, 3, 3]} # {1, 4, 9}
🔧 实用操作技巧
- enumerate 获取索引和值
fruits = ['apple', 'banana', 'cherry']
# 传统方式(不推荐)
for i in range(len(fruits)):
print(i, fruits[i])
# Pythonic 方式
for i, fruit in enumerate(fruits):
print(i, fruit)
# 指定起始索引
for i, fruit in enumerate(fruits, start=1):
print(i, fruit) # 从1开始计数
- zip 并行迭代多个序列
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# 转换为字典
score_dict = dict(zip(names, scores)) # {'Alice': 85, 'Bob': 92, 'Charlie': 78}
- 使用 collections 模块
from collections import defaultdict, Counter
# defaultdict - 自动初始化字典值
word_count = defaultdict(int)
for word in ['apple', 'banana', 'apple']:
word_count[word] += 1 # 不会报 KeyError
# Counter - 计数神器
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts.most_common(2)) # [('apple', 3), ('banana', 2)]
⚡ 高效编程技巧
- 使用 any() 和 all()
numbers = [1, 3, 5, 7, 9]
# 检查是否有偶数
has_even = any(x % 2 == 0 for x in numbers) # False
# 检查是否都是奇数
all_odd = all(x % 2 == 1 for x in numbers) # True
- 使用 set 去重和快速查找
# 列表去重(保持顺序)
original = [3, 1, 2, 3, 4, 2, 1]
unique = list(dict.fromkeys(original)) # [3, 1, 2, 4]
# 快速成员检查
large_list = list(range(1000000))
large_set = set(large_list)
# 列表查找(慢)
print(999999 in large_list) # O(n)
# 集合查找(快)
print(999999 in large_set) # O(1)
- 使用 get() 方法安全访问字典
person = {'name': 'Alice', 'age': 25}
# 不安全的方式
# city = person['city'] # KeyError!
# 安全的方式
city = person.get('city', 'Unknown') # 返回 'Unknown'
age = person.get('age') # 返回 25
🎨 代码优化技巧
- 使用 with 语句管理资源
# 自动关闭文件
with open('file.txt', 'r') as file:
content = file.read()
# 文件在这里自动关闭
# 自定义上下文管理器
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
print(f"耗时: {time.time() - start:.2f}秒")
with timer():
# 执行一些操作
time.sleep(1)
- 使用生成器节省内存
# 列表(占用内存)
def get_numbers_list(n):
return [x for x in range(n)] # 一次性生成所有数字
# 生成器(节省内存)
def get_numbers_gen(n):
for x in range(n):
yield x # 按需生成
# 使用
for num in get_numbers_gen(1000000): # 几乎不占内存
if num > 10:
break
- 使用 args 和 kwargs
def flexible_function(*args, **kwargs):
print(f"位置参数: {args}")
print(f"关键字参数: {kwargs}")
flexible_function(1, 2, 3, name='Alice', age=25)
# 位置参数: (1, 2, 3)
# 关键字参数: {'name': 'Alice', 'age': 25}
🚀 高级技巧
- 使用 walrus operator (海象运算符 := )
# Python 3.8+
while (line := input("输入内容: ")) != "quit":
print(f"你输入了: {line}")
# 在列表推导式中使用
data = [1, 2, 3, 4, 5]
results = [y for x in data if (y := x * 2) > 5] # [6, 8, 10]
- 使用 functools.lru_cache 缓存结果
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# 第一次计算会慢,后续相同参数会直接从缓存返回
print(fibonacci(100)) # 快速返回结果
- 使用 dataclasses 简化类定义
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
city: str = "Unknown" # 默认值
# 自动生成 __init__, __repr__, __eq__ 等方法
person = Person("Alice", 25)
print(person) # Person(name='Alice', age=25, city='Unknown')
💡 调试与测试技巧
- 使用 assert 进行断言
def calculate_discount(price, discount):
assert 0 <= discount <= 1, "折扣必须在0-1之间"
assert price >= 0, "价格不能为负"
return price * (1 - discount)
- 使用 str 和 repr
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
p = Point(3, 4)
print(str(p)) # Point(3, 4) - 用户友好
print(repr(p)) # Point(x=3, y=4) - 开发者友好
📝 总结建议
- 写Pythonic的代码:利用语言特性,避免"翻译"其他语言的写法
- 善用标准库:Python 有"内置电池",很多问题都有现成解决方案
- 注重可读性:代码是写给人看的,偶尔才给机器执行
- 适时优化:先写正确的代码,再考虑优化性能
- 多写文档字符串:用 “”“注释”"" 说明函数/类的用途
这些技巧会让你的 Python 代码更简洁、高效和专业!
更多推荐

所有评论(0)