字典上的计时del运算符,keyror?

2024-03-29 15:24:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在为我正在学习的一个类编写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

我不知道为什么我会得到这个错误,或者如何修复它,就我所知,错误引用的键是存在的,但不能删除?任何帮助都将不胜感激


Tags: inpybuildself错误linedictfile
1条回答
网友
1楼 · 发布于 2024-03-29 15:24:40

您的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

相关问题 更多 >