# 日常代码笔记，python的推导式&性能评估

01

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)

dis输出的字节码如下：

4 0 BUILD_LIST 0

2 STORE_FAST 0 (z)

5 4 SETUP_LOOP 46 (to 52)

10 CALL_FUNCTION 1

12 GET_ITER

>> 14 FOR_ITER 34 (to 50)

16 STORE_FAST 1 (i)

22 BINARY_MODULO

26 COMPARE_OP 2 (==)

28 POP_JUMP_IF_FALSE 14

36 STORE_FAST 2 (j)

44 CALL_FUNCTION 1

46 POP_TOP

48 JUMP_ABSOLUTE 14

>> 50 POP_BLOCK

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)

4 MAKE_FUNCTION 0

10 CALL_FUNCTION 1

12 GET_ITER

14 CALL_FUNCTION 1

16 STORE_FAST 0 (z)

20 RETURN_VALUE

### 字典推导式

mix = {'m': 300, 'i': 500,'x':1000}

lab = {v: k for k,v in mix.items()}

print(lab)

# {300:"m",500:"i",1000:"x"}

03

HackerRank

codepen