这里,del运算符是定时的:
method=POST
这一次,它是运行运算符而不是del运算符所需的时间。需要更改和添加哪些代码?
答案 0 :(得分:0)
你需要为list和dict分别实现del,因为list将整数转换为索引,你的字典有字符串键。由于我们无法删除列表或字典中不存在的元素,因此我省略了该部分。
from timeit import Timer
def build_list(n):
return list(range(n)) # create list of 1 to n
def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
return {i: str(i) for i in range(n)} # from last listing in this chapter
def delx(x, n): # do in front, middle, end, and not found
if x is list:
del x[0] # deleting first element in list
del x[(n-1)//2] # middle element delete n-1 because 0-th element is already deleted
del x[-1] # last element delete
if x is dict:
del x[str(0)] # deleting first element in dict
del x[str((n-1)//2)] # deleting middle element from dict
del x[str((n-2)-1)] # last element delete n-2 because 0-th and middle element is already deleted
# str("a") in x # not in it
timeList = Timer(
"delx(x,n)",
"from __main__ import n,build_list,delx; x = build_list(n)")
timeDict = Timer(
"delx(x,n)",
"from __main__ import n,build_dict,delx; x = build_dict(n)")
# get min of 5 runs of 5
print("N", "\t", "List", "\t", "Dict")
for size in range(1000, 100000+1, 5000): # sizes to graph for n:
n = size
list_secs = timeList.repeat(5,5)
dict_sect = timeDict.repeat(5,5)
print(n, "\t", min(list_secs), "\t", min(dict_sect))