昨天敲代码时突然想到一个问题,列表的遍历和生成器的遍历的效率哪个高,也就是for i in [0, 1, 2, 3, 4] 和for i in range(5)这两个表达式哪个效率高?话不多说,上代码
1 import time 2 i = 0 3 l1 = [] 4 while i < 10000000: 5 l1.append(i) 6 i += 1 7 8 l2 = [] 9 list_start_time = time.time() 10 for j in l1: 11 l2.append(j) 12 list_end_time = time.time() 13 list_time = list_end_time - list_start_time 14 print("list_time", list_time) 15 16 l3 = [] 17 range_start_time = time.time() 18 for i in range(10000000): 19 l3.append(i) 20 range_end_time = time.time() 21 range_time = range_end_time - range_start_time 22 print("range_time", range_time)
运行结果如下
list_time 2.888223648071289 range_time 3.6887366771698 Process finished with exit code 0
可见range生成器遍历的效率比列表遍历的低,为什么呢?