在Python中比较del for dict和list的性能时出错

时间:2016-06-26 07:12:54

标签: python list dictionary

我正在使用算法和数据结构进行问题解决的编程练习。练习是比较列表和字典上del运算符的性能,这里是代码:

import timeit, random
from timeit import Timer

for i in range(1000000, 100000000, 1000000):
    x = list(range(i))
    t = Timer("del x[random.randrange(%d)]" %i,\
              "from __main__ import random,x")

    y = {j: None for j in range(i)}
    key = random.choice(list(y.keys()))
    t1 = Timer("del y[%d]" %key,\
               "from __main__ import y")

    time1 = t1.timeit(number=1000)          
    time = t.timeit(number=1000)

    print("%d, %15.5f, %15.5f" % (i, time, time1))

这是错误:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\Problem_Solving\chapter2_del_list_dict.py", line 17, in <module>
    time = t.timeit(number=1000)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\timeit.py", line 178, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
IndexError: list assignment index out of range

有时候:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\Problem_Solving\chapter2_del_list_dict.py", line 18, in <module>
    time1 = t1.timeit(number=1000)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\timeit.py", line 178, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
KeyError: 280015

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

定时片段的所有重复都在同一x上运行。因此,一旦删除了一个元素,列表就会缩短,然后在删除另一个元素后,它会更短,依此类推。最终,您可能会随机尝试删除不再存在的索引,因为列表已经太短了。

您的第二个示例,使用dict,将始终失败,因为您正在选择要在整个timeit代码段之外删除哪个键。因此,在第一次运行时,它将删除一个密钥,然后在第二次运行时它将尝试再次删除相同的密钥,这将失败,因为该密钥不再存在。