Python - 哪个初始化列表更快?
pythonserver side programmingprogramming更新于 2025/9/17 12:28:17
Python 是一种非常灵活的语言,其中可以通过多种方式执行单个任务,例如初始化列表可以通过多种方式执行。但是,这些看似相似的方法之间存在细微的差异。Python 因其简单性和可读性而广受欢迎,但与 C++ 或 Java 相比,它同样因速度慢而臭名昭著。‘for’ 循环尤其以速度慢而闻名,而像 map() 和 filter() 这样的方法则以速度快而闻名,因为它们是用 C 编写的。
示例
# 导入时间模块以计算时间
导入时间
# 初始化列表以保存时间
forLoopTime = []
whileLoopTime = []
listComprehensionTime = []
starOperatorTime = []
# 重复该过程 500 次
# 并计算平均所用时间。
for k in range(500):
# 开始时间
start = time.time()
# 声明空列表
a = []
# 运行 for 循环 10000 次
for i in range(10000):
a.append(0)
# 停止时间
stop = time.time()
forLoopTime.append(stop-start)
# 开始时间
start = time.time()
# 声明空列表
a = []
i = 0
# 运行 for 循环 10000 次
while(i<10000):
a.append(0)
i+= 1
stop = time.time()
whileLoopTime.append(stop-start)
start = time.time()
# 使用列表推导来初始化列表
a = [0 for i in range(10000)]
stop = time.time()
listComprehensionTime.append(stop-start)
start = time.time()
# 使用 * 运算符
a = [0]*10000
stop = time.time()
starOperatorTime.append(stop-start)
print("for 循环所用的平均时间:" + str(sum(forLoopTime)/100))
print("while 循环所用的平均时间:" + str(sum(whileLoopTime)/100))
print("列表推导所用的平均时间:" + str(sum(listComprehensionTime)/100))
print("* 运算符所用的平均时间:" + str(sum(starOperatorTime)/100))
输出
for 循环所用的平均时间:0.00623725175858 while 循环所用的平均时间:0.00887670278549 列表推导所用的平均时间:0.00318484544754 * 运算符所用的平均时间:0.000371544361115
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

