Python - 初始化列表哪种更快?


Python 是一种非常灵活的语言,一项单一任务可以用许多种方式完成,例如初始化列表可以采用多种方式。但是,这些看上去相似的方法之间存在细微的差别。Python 因其简单性和可读性广受欢迎,但也因与 C++ 或 Java 相比执行速度慢而同样声名狼藉。“for” 循环尤其以慢而闻名,而 map() 和 filter() 等方法以快而著称,因为它们是用 C 编写的。

示例

 在线演示

# import time module to calculate times
import time
# initialise lists to save the times
forLoopTime = []
whileLoopTime = []
listComprehensionTime = []
starOperatorTime = []
# repeat the process for 500 times
# and calculate average of times taken.
for k in range(500):
   # start time
   start = time.time()
   # declare empty list
   a = []
   # run a for loop for 10000 times
   for i in range(10000):
      a.append(0)
   # stop time
   stop = time.time()
   forLoopTime.append(stop-start)
   # start time
   start = time.time()
   # declare an empty list
   a = []
   i = 0
   # run a for loop 10000 times
   while(i<10000):
      a.append(0)
      i+= 1
   stop = time.time()
   whileLoopTime.append(stop-start)
   start = time.time()
   # list comprehension to initialize list
   a = [0 for i in range(10000)]
   stop = time.time()
   listComprehensionTime.append(stop-start)
   start = time.time()
   # using the * operator
   a = [0]*10000
   stop = time.time()
   starOperatorTime.append(stop-start)
print("Average time taken by for loop: " + str(sum(forLoopTime)/100))
print("Average time taken by while loop: " + str(sum(whileLoopTime)/100))
print("Average time taken by list comprehensions: " + str(sum(listComprehensionTime)/100))
print("Average time taken by * operator: " + str(sum(starOperatorTime)/100))    

输出

Average time taken by for loop: 0.00623725175858
Average time taken by while loop: 0.00887670278549
Average time taken by list comprehensions: 0.00318484544754
Average time taken by * operator: 0.000371544361115

更新于: 08-8-2020

143 次浏览

开启你的职业

完成课程并获取认证

开始
广告