日常代码笔记,python的推导式&性能评估
import time
t1=time.time()
z=[]
for i in range(100000):
if i%2==0:
j=i+3
z.append(j)
t2=time.time()
print(t2-t1)
t1=time.time()
z=[i+3 for i in range(100000) if i%2==0]
t2=time.time()
print(t2-t1)
import dis
def f1():
z=[]
for i in range(10000):
if i%2==0:
j=i+3
z.append(j)
def f2():
z=[i+3 for i in range(10000) if i%2==0]
dis.dis(f1)
4 0 BUILD_LIST 0
2 STORE_FAST 0 (z)
5 4 SETUP_LOOP 46 (to 52)
6 LOAD_GLOBAL 0 (range)
8 LOAD_CONST 1 (10000)
10 CALL_FUNCTION 1
12 GET_ITER
>> 14 FOR_ITER 34 (to 50)
16 STORE_FAST 1 (i)
6 18 LOAD_FAST 1 (i)
20 LOAD_CONST 2 (2)
22 BINARY_MODULO
24 LOAD_CONST 3 (0)
26 COMPARE_OP 2 (==)
28 POP_JUMP_IF_FALSE 14
7 30 LOAD_FAST 1 (i)
32 LOAD_CONST 4 (3)
34 BINARY_ADD
36 STORE_FAST 2 (j)
8 38 LOAD_FAST 0 (z)
40 LOAD_ATTR 1 (append)
42 LOAD_FAST 2 (j)
44 CALL_FUNCTION 1
46 POP_TOP
48 JUMP_ABSOLUTE 14
>> 50 POP_BLOCK
>> 52 LOAD_CONST 0 (None)
54 RETURN_VALUE
def f2():
z=[i+3 for i in range(10000) if i%2==0]
dis.dis(f2)
10 0 LOAD_CONST 1 (<code object <listcomp> at 0x10bb6c420)
2 LOAD_CONST 2 ('f2.<locals>.<listcomp>')
4 MAKE_FUNCTION 0
6 LOAD_GLOBAL 0 (range)
8 LOAD_CONST 3 (10000)
10 CALL_FUNCTION 1
12 GET_ITER
14 CALL_FUNCTION 1
16 STORE_FAST 0 (z)
18 LOAD_CONST 0 (None)
20 RETURN_VALUE
02
字典推导式
mix = {'m': 300, 'i': 500,'x':1000}
lab = {v: k for k,v in mix.items()}
print(lab)
# {300:"m",500:"i",1000:"x"}
codepen
是一个完全免费的前端代码托管服务,上面有很多特效代码,也是我常逛的~
赞 (0)