1、使用for
代码语言:javascript
复制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)) # <class 'list'>
print(datetime.now()-start_time) # 0:00:27.886609
2、使用list
代码语言:javascript
复制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) # 0:00:13.985333
3、set
代码语言:javascript
复制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(type(img2)) # <class 'set'>
print(datetime.now()-start_time) # 0:00:15.446309
4、附加 dict
代码语言:javascript
复制import numpy as np
from datetime import datetime
img=np.linspace(0,100,1000000)
start_time=datetime.now()
img2={x:x**2 for x in img}
print(type(img2)) # <class 'dict'>
print(datetime.now()-start_time) # 0:00:00.685456