你的方法似乎很合理。我尝试了一个更好的使用np.nditer
,但你的仍然是两倍快:
import numpy as np
class Foo():
def foo(self):
return np.random.random()
a = np.empty((10,10), dtype=object)
for ind,v in np.ndenumerate(a):
a[ind] = Foo()
def evaluate_and_reshape(a, shape):
it = np.nditer( op = [a.reshape(shape),None],
flags = ['multi_index','refs_ok'],
op_flags = [['readonly'],
['writeonly','allocate']],
op_dtypes = [object, float],
itershape = (shape)
)
while not it.finished:
ind = it.multi_index
it.operands[1][ind] = it.operands[0][ind].foo()
it.iternext()
return it.operands[1]
def sol1():
return evaluate_and_reshape(a,(20,5))
def sol2():
return np.reshape( [o.foo() for o in a.flat], (20,5) )
定时:
timeit sol1()
#10000 loops, best of 3: 110 us per loop
timeit sol2()
#10000 loops, best of 3: 54.8 us per loop