5个让你代码更优雅的Python技巧
Python 以简洁著称,但用好技巧才能真正写出“Pythonic”的代码。分享几个我常用的写法,帮你少写循环、少踩坑。
1. 列表推导代替 map/filter
# 不推荐
squares = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, range(10))))
# Pythonic
squares = [x**2 for x in range(10) if x % 2 == 0]
2. 使用 zip 并行遍历
names = ["Alice", "Bob"]
scores = [95, 87]
for name, score in zip(names, scores):
print(f"{name}: {score}")
3. 上下文管理器自动释放资源
with open("data.txt", "r") as f:
content = f.read()
# 文件自动关闭,无需手动 f.close()
4. 用 enumerate 获取索引和值
for i, item in enumerate(["a", "b", "c"], start=1):
print(i, item) # 1 a, 2 b, 3 c
5. 生成器节省内存
处理大文件时,用生成器逐行读取:
def read_large(file_path):
with open(file_path) as f:
for line in f:
yield line.strip()
这些技巧能让代码更短、更清晰。你还有哪些私藏的 Python 写法?欢迎留言分享!