从测验结果可以看出,python列表的底层数据结构为数组
append:O1
insert尾部:接近O1,慢于append
insert头部:On
pop:O1
pop头部:On
__setitem__:O1
__getitem__:O1
contain:On
测验代码:
def cat_runtime(f):
def wrap(*args, **kwargs):
st = time.time()
f(*args, **kwargs)
print(f'{f.__name__}: {time.time() - st}')
return wrap
@cat_runtime
def ls_append(ls):
# 0.006
for i in range(100000):
ls.append(1)
@cat_runtime
def ls_insert9(ls):
# 0.01
for i in range(100000):
ls.insert(300000, 1)
@cat_runtime
def ls_insert0(ls):
# 5
for i in range(100000):
ls.insert(0, 1)
@cat_runtime
def ls_pop(ls):
# 0.006
while ls:
ls.pop()
@cat_runtime
def ls_pop0(ls):
# 0.86
while ls:
ls.pop(0)
@cat_runtime
def ls_set(ls):
# 0.003
for i in range(100000):
ls[50000] = 1
@cat_runtime
def ls_get(ls):
# 0.003
for i in range(100000):
a = ls[50000]
@cat_runtime
def ls_in(ls):
# 0.003
for i in range(100000):
a = (50000 in ls)
def main():
ls = list(range(100000))
ls_append(ls.copy())
ls_pop(ls.copy())
ls_pop0(ls.copy())
ls_set(ls.copy())
ls_get(ls.copy())
ls_in(ls.copy())
main()