【问题标题】:Timing del operator on dictionaries, KeyError?字典上的时间 del 运算符,KeyError?
【发布时间】:2015-10-16 21:25:29
【问题描述】:

我一直在为我正在上的一门课做 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(最近一次调用最后一次): 文件“/Users/mcastro/PycharmProjects/untitled1/testdel.py”,第 21 行,在 dict_secs = timeDict.repeat(5,5) 文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py”,第 206 行,重复 t = self.timeit(数字) 文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py”,第 178 行,时间 计时 = self.inner(它,self.timer) 文件“”,第 6 行,在内部 文件“/Users/mcastro/PycharmProjects/untitled1/testdel.py”,第 10 行,字典 x 删除 x[0] 关键错误:0

据我了解,错误引用的键存在但无法删除,我无法弄清楚为什么会出现此错误或如何修复它?任何帮助将不胜感激

【问题讨论】:

    标签: python dictionary timer timeit del


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 2016-06-16
      • 2021-02-01
      相关资源
      最近更新 更多