python循环优化
python中经常使用到for循环,需要消耗大量时间,本文将介绍一些简单的方法进行提速。
列表推导式
使用列表推导式,加快运行速度
1 2 3 4 5 6
| def Calculate_raw(list_numbers): list_results = [] for n in list_numbers: list_results.append(n**3) return list_results
|
1 2 3 4
| def Calculate_optimization(list_numbers): list_results = [n**3 for n in list_numbers]
|
减少内部计算
在循环之外计算好列表的长度
1 2 3 4 5 6 7
| def Calculate_raw(list_number): list_results = [] for n in range(len(list_number)): list_results.append(n ** 3) return list_results
|
1 2 3 4 5 6 7 8
| def Calculate_optimization(list_number): list_results = [] len_number = len(list_number) for n in range(len_number): list_results.append(n ** 3) return list_results
|
map函数
map函数是用C语言编写,并且经过了优化
1 2 3 4 5 6 7 8 9 10
| def Func(x): return x ** 3
def Calculate_raw(list_number): list_results = [] for n in range(len(list_number)): list_results.append(Func(n)) return list_results
|
1 2 3 4 5 6 7 8
| def Func(x): return x ** 3
def Calculate_optimization(list_number): list_results = map(Func, list_number) return list_results
|
向量化
将数据向量化
1 2 3 4 5 6 7 8 9
| import numpy as np
def Calculate_raw(n): results = 0 for i in range(n): results = results + i return results
|
1 2 3 4 5 6 7
| import numpy as np
def Calculate_optimization(n): results = np.sum(np.arange(n)) return results
|
join连接字符串
join连接字符串快于使用+
号
1 2 3 4 5 6 7
| def Calculate_raw(list_strs): results = "" for i_str in range(n): results = results + i_str return results
|
1 2 3 4 5 6
|
def Calculate_optimization(list_strs): results = "".join(list_strs) return results
|