python列表各方法性能情况

从测验结果可以看出,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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值