1. 程式人生 > >python 優化迴圈

python 優化迴圈

for迴圈

import numpy as np
from datetime import datetime

img=np.random.random([10000,10000])

start_time=datetime.now()
img2=[]
for i in img:
    for j in i:
        if j > 0.5:
            img2.append(1.)
        else:
            img2.append(0.)
print(type(img2)) 
print(datetime.now()-start_time) 

list列表

import numpy as np
from datetime import datetime

img=np.random.random([10000,10000])

start_time=datetime.now()
img2=[1. if j>0.5 else 0. for i in img for j in i]
print(datetime.now()-start_time) 

set集合

img=np.random.random([10000,10000])

start_time=datetime.now()
img2={1. if j>0.5 else 0. for i in img for j in i}
print(type(img2)) 
print(datetime.now()-start_time) 

字典

img=np.linspace(0,100,1000000)

start_time=datetime.now()
img2={x:x**2 for x in img}
print(type(img2)) 
print(datetime.now()-start_time)