标签:body 结果 int notebook 整数 org stream 数据结构 操作性
2019-11-03 16:07:33
## 对比*list*和*dict*操作
类型 | list | dict |
索引 | i | key |
添加 | append、extend、insert | d[key] = value |
删除 | pop、remove* | pop |
更新 | l[i] = value | d[key] = value |
正查 | l[i]、l[i:j] | d[key]、copy |
反查 | index(value)、count(value) | / |
其他 | reverse、sort | has_key、update |
原则上,常用操作性能最优
# list
对列表:最常用操作有
+ 按索引赋值取值:`l[i]=v` `v=l[i]`
+ 列表增长:
- append()
- __add()__
- "+"
四种生成前n个整数列表的方法
#循环连接 def test1(): l = [] for i in range(1000): l = l + [i] #append()方法 def test2(): l = [] for i in range(1000): l.append(i) #列表推导式 def test3(): l = [i for i in range(1000)] #range()函数调用转成列表 def test4(): l = list(range(1000))
性能对比
from timeit import Timer t1 = Timer("test1()", "from __main__ imporrt test1") print("concat %f seconds\n" % t1.timeit(number = 1000)) t2 = Timer("test2()", "from __main__ imporrt test2") print("append %f seconds\n" % t2.timeit(number = 1000)) t3 = Timer("test3()", "from __main__ imporrt test3") print("comprehension %f seconds\n" % t3.timeit(number = 1000)) t4 = Timer("test4()", "from __main__ imporrt test4") print("list range %f seconds\n" % t4.timeit(number = 1000))
- timeit模块Timer.timeit()方法[number]参数表示反复调用多少次
运行结果1<2<3<4
concat 1.082888 seconds append 0.054237 seconds comprehension 0.027933 seconds list range 0.011302 seconds
## list.pop操作
比较pop()和pop(i)
import timeit popzero = timeit.Timer("x.pop(0)", "from __main__ import x") popend = timeit.Timer("x.pop()", "from __main__ import x") x = list(range(2000000)) print(popzero.timeit(number=1000)) x = list(range(2000000)) print(popend.timeit(number=1000))
运行结果
1.5929707000000235 5.389999989802163e-05
比较两者时间增长趋势
print("\tpop(0)\t\t\tpop()") for i in range(1000000,100000001,1000000): x = list(range(i)) pt = popend.timeit(number=1000) x = list(range(i)) pz = popzero.timeit(number=1000) print("%15.5f, %15.5f"%(pz,pt))
标签:body 结果 int notebook 整数 org stream 数据结构 操作性
原文地址:https://www.cnblogs.com/ilyyfan/p/11788222.html