python 優化迴圈
阿新 • • 發佈:2018-11-14
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)