2019-11-03 16:07:33
## Comparison * list * and * dict * Operation
Types of | list | dict |
index | i | key |
Add to | append、extend、insert | d[key] = value |
delete | pop、remove* | pop |
Update | l[i] = value | d[key] = value |
Positive check | l[i]、l[i:j] | d[key]、copy |
Reverse Lookup | index(value)、count(value) | / |
other | reverse、sort | has_key、update |
In principle, the best performance for common operations
# list
List: The most common operations have
Assignment Index Value + Press: `l [i] = v`` v = l [i] `
+ List Growth:
- append()
- __add()__
- "+"
The method of generating four kinds of the first n integers list
# Loop connection DEF test1 (): L = [] for I in Range (1000 ): L = L + [I] # the append () method DEF test2 (): L = [] for I in Range (1000 ): L .append (I) # listing derived formula DEF Test3 (): L = [I for I in Range (1000 )] # Range () function call to the forwarding list DEF Test4 (): L = list (Range (1000))
Performance Comparison
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 module Timer.timeit () method [number] parameter indicates how many times repeated calls
Results Run 1 <2 <3 <4
concat 1.082888 seconds append 0.054237 seconds comprehension 0.027933 seconds list range 0.011302 seconds
## list.pop operation
Comparative pop () and 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))
operation result
1.5929707000000235 5.389999989802163e-05
Compare the two time growth trend
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))