本文目录导读:

- 列表推导式替代for循环
- 使用map()函数
- 局部变量引用优化
- 使用enumerate替代索引访问
- 避免在循环中使用if else分支
- 使用numpy进行数值计算
- 使用循环展开技术
- 实际案例:字符串处理优化
- 性能测试对比
我来分享几个Python循环优化的实际案例,从简单到复杂逐步提升性能。
列表推导式替代for循环
优化前 (普通循环):
# 创建平方数列表
squares = []
for i in range(1000000):
squares.append(i ** 2)
优化后 (列表推导式):
squares = [i ** 2 for i in range(1000000)] # 性能提升:约40-60%
使用map()函数
优化前:
names = ['Alice', 'Bob', 'Charlie', 'David']
upper_names = []
for name in names:
upper_names.append(name.upper())
优化后:
names = ['Alice', 'Bob', 'Charlie', 'David'] upper_names = list(map(str.upper, names)) # 性能提升:约20-30%
局部变量引用优化
优化前:
import math
def calculate_distances(points):
distances = []
for point in points:
dist = math.sqrt(point[0]**2 + point[1]**2)
distances.append(dist)
return distances
优化后:
import math
def calculate_distances(points):
# 将全局函数赋给局部变量
sqrt = math.sqrt
distances = []
for point in points:
dist = sqrt(point[0]**2 + point[1]**2)
distances.append(dist)
return distances
# 性能提升:约15-25%
使用enumerate替代索引访问
优化前:
data = ['a', 'b', 'c', 'd', 'e']
result = []
for i in range(len(data)):
result.append(f"Index {i}: {data[i]}")
优化后:
data = ['a', 'b', 'c', 'd', 'e']
result = [f"Index {i}: {item}" for i, item in enumerate(data)]
# 性能提升+代码更简洁
避免在循环中使用if else分支
优化前:
def process_list(items):
result = []
for item in items:
if item % 2 == 0:
result.append(item * 2)
else:
result.append(item + 1)
return result
优化后:
def process_list(items):
# 使用条件表达式
return [item * 2 if item % 2 == 0 else item + 1 for item in items]
使用numpy进行数值计算
优化前 (纯Python循环):
import numpy as np
def sum_squares_pure(n):
total = 0
for i in range(n):
total += i ** 2
return total
优化后 (numpy向量化):
import numpy as np
def sum_squares_numpy(n):
arr = np.arange(n)
return np.sum(arr ** 2)
# 性能提升:当n=1000000时,提升约100倍
使用循环展开技术
优化前:
def process_data(data):
result = 0
for value in data:
result += value * 2
result += value * 3
return result
优化后:
def process_data_unrolled(data):
result = 0
i = 0
length = len(data)
# 一次处理4个元素
while i + 3 < length:
result += data[i] * 2 + data[i] * 3
result += data[i+1] * 2 + data[i+1] * 3
result += data[i+2] * 2 + data[i+2] * 3
result += data[i+3] * 2 + data[i+3] * 3
i += 4
# 处理剩余元素
while i < length:
result += data[i] * 2 + data[i] * 3
i += 1
return result
# 性能提升:约10-20%
实际案例:字符串处理优化
优化前:
def process_text_lines(lines):
results = []
for line in lines:
line = line.strip()
if line.startswith('#'):
continue
parts = line.split(',')
if len(parts) >= 3:
results.append({
'name': parts[0],
'age': int(parts[1]),
'city': parts[2]
})
return results
优化后:
def process_text_lines_fast(lines):
# 使用生成器表达式和条件过滤
return [
{'name': parts[0], 'age': int(parts[1]), 'city': parts[2]}
for line in lines
if not line.startswith('#')
and len((parts := line.strip().split(','))) >= 3
]
# 性能提升:约30-50%,代码更简洁
性能测试对比
import timeit
# 测试列表推导式 vs 普通循环
def test_performance():
# 设置
setup_code = """
import random
data = [random.randint(1, 100) for _ in range(1000000)]
"""
# 测试普通循环
loop_code = """
result = []
for x in data:
result.append(x ** 2)
"""
# 测试列表推导式
comprehension_code = """
result = [x ** 2 for x in data]
"""
loop_time = timeit.timeit(loop_code, setup_code, number=10)
comp_time = timeit.timeit(comprehension_code, setup_code, number=10)
print(f"普通循环: {loop_time:.4f}秒")
print(f"列表推导式: {comp_time:.4f}秒")
print(f"提升: {(loop_time - comp_time) / loop_time * 100:.1f}%")
# test_performance()
- 减少函数调用开销:将循环内频繁调用的函数提到循环外
- 使用内置函数:
map(),filter(),reduce()等 - 向量化操作:对于数值计算使用NumPy
- 避免动态类型检查:使用局部变量引用
- 使用生成器:大数据集时内存效率更高
- 并行处理:对于CPU密集型任务使用
multiprocessing
优化的前提是先有正确的代码,再考虑性能,而且要用profiler确定真正的性能瓶颈在哪里。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播