字典上的 Timing del 运算符,KeyError?

Timing del operator on dictionaries, KeyError?

我一直在为我正在接受的 class 做一个 python 作业,但我不知道如何克服这个 KeyError。我正在尝试对 python 中的字典使用 del 运算符计时,这是我的代码:

from timeit import Timer


def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
    return {i : str(i) for i in range(n)}  

def dictionaryx(x,n):
    del x[0]
    del x[n//2]
    del x[n-1]

timeDict = Timer(
    "dictionaryx(x,n)",
    "from __main__ import n,build_dict,dictionaryx; x = build_dict(n)")


for size in range(1000, 100000+1, 5000):
    n = size
    dict_secs = timeDict.repeat(5,5)
    print(n, "\t", min(dict_secs))

每次我尝试运行此代码时,我都会收到以下错误

Traceback (most recent call last): File "/Users/mcastro/PycharmProjects/untitled1/testdel.py", line 21, in dict_secs = timeDict.repeat(5,5) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 206, in repeat t = self.timeit(number) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 178, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner File "/Users/mcastro/PycharmProjects/untitled1/testdel.py", line 10, in dictionaryx del x[0] KeyError: 0

据我所知,错误所引用的键存在但无法删除,我不知道为什么会收到此错误或如何修复它?任何帮助将不胜感激

您的 timeit 循环每次都使用相同的字典 x。第一次调用 dictionaryx(x,n) 时,它会删除元素 0,因此下次调用时它不存在了。

def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
    return {i : str(i) for i in range(n)}

def dictionaryx(x,n):
    del x[0]
    del x[n//2]
    del x[n-1]

n = 1000
x = build_dict(n)
dictionaryx(x,n)    # this deletes x[0]
dictionaryx(x,n)    # this causes the error