Python 编程进阶——10个提升效率的实用技巧
·
Python 语法简单,但用好它的高级特性可以让代码更简洁、更高效。这篇文章总结了 10 个日常开发中最实用的 Python 技巧。
1. 列表推导式
代替传统 for 循环,一行搞定:
# ❌ 传统写法
squares = []
for i in range(10):
squares.append(i * i)
# ✅ 列表推导式(一行搞定)
squares = [i * i for i in range(10)]
# 带条件筛选
even_squares = [i * i for i in range(10) if i % 2 == 0]
# 结果: [0, 4, 16, 36, 64]
2. 字典合并
# Python 3.9+
dict1 = {"name": "张三", "age": 20}
dict2 = {"class": "大数据2301", "score": 88}
# ✅ 使用 | 运算符
merged = dict1 | dict2
print(merged)
# {'name': '张三', 'age': 20, 'class': '大数据2301', 'score': 88}
3. f-string 格式化
name = "张三"
score = 88.5
# ✅ f-string(推荐)
print(f"{name} 的成绩是 {score} 分")
print(f"{name} 的成绩是 {score:.1f} 分") # 保留一位小数
print(f"{name:10} 的成绩") # 左对齐,占10位
print(f"分数: {score:>6.1f}") # 右对齐,共6位
4. enumerate 获取索引
students = ["张三", "李四", "王五"]
# ❌ 传统写法
for i in range(len(students)):
print(i, students[i])
# ✅ enumerate
for i, name in enumerate(students, start=1):
print(f"第{i}名: {name}")
# 输出:
# 第1名: 张三
# 第2名: 李四
# 第3名: 王五
5. zip 并行遍历
names = ["张三", "李四", "王五"]
scores = [88, 92, 76]
classes = ["大数据2301", "大数据2301", "大数据2302"]
# 同时遍历多个列表
for name, score, cls in zip(names, scores, classes):
print(f"{name} - {cls} - {score}分")
# 合并为字典
result = dict(zip(names, scores))
print(result) # {'张三': 88, '李四': 92, '王五': 76}
6. 使用 collections 模块
from collections import Counter, defaultdict
# Counter:统计频数
scores = [85, 92, 78, 85, 92, 85, 60]
count = Counter(scores)
print(count) # Counter({85: 3, 92: 2, 78: 1, 60: 1})
print(count.most_common(2)) # [(85, 3), (92, 2)]
# defaultdict:自动初始化
data = defaultdict(list)
data["A班"].append("张三")
data["A班"].append("李四")
data["B班"].append("王五")
print(dict(data)) # {'A班': ['张三', '李四'], 'B班': ['王五']}
7. any / all 判断
scores = [85, 92, 45, 78, 60]
# 是否有不及格的?
has_fail = any(s < 60 for s in scores) # True
# 是否都及格了?
all_pass = all(s >= 60 for s in scores) # False
# 是否都没有优秀(>=90)?
no_excellent = all(s < 90 for s in scores) # False
8. lambda 匿名函数
students = [
{"name": "张三", "score": 88},
{"name": "李四", "score": 92},
{"name": "王五", "score": 76},
]
# 按成绩排序
students.sort(key=lambda s: s["score"], reverse=True)
# 提取字段
names = list(map(lambda s: s["name"], students))
print(names) # ['李四', '张三', '王五']
9. 文件操作利器——pathlib
from pathlib import Path
# 创建路径
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)
# 遍历文件
for f in data_dir.glob("*.csv"):
print(f.name) # 文件名
print(f.stem) # 不带后缀
print(f.suffix) # 后缀名
print(f.stat().st_size) # 文件大小
# 读写文件
Path("output.txt").write_text("Hello", encoding="utf-8")
content = Path("output.txt").read_text(encoding="utf-8")
10. 装饰器——统计函数耗时
import time
from functools import wraps
def timer(func):
"""统计函数执行时间的装饰器"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
cost = time.time() - start
print(f"{func.__name__} 耗时: {cost:.3f}秒")
return result
return wrapper
@timer
def calculate_sum(n):
return sum(range(n))
result = calculate_sum(10000000)
print(f"结果: {result}")
# 输出:
# calculate_sum 耗时: 0.256秒
# 结果: 49999995000000
总结
这 10 个技巧覆盖了日常开发中最常用的 Python 高级特性。建议收藏起来,写代码时翻一翻,慢慢养成习惯后代码质量和效率都会明显提升。
💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!每周更新 Java/Python/爬虫 实战干货,不让你白来。
更多推荐
所有评论(0)