Skip to main content
 首页 » 编程设计

python之获取数组,它是对对象数组的每个元素调用函数的结果

2025年05月04日14lyj

获取函数调用结果数组的选项有哪些 在给定(对象)数组的每个元素上?

我现在做的是:

object_array # an array whose elements are objects 
result_array=scipy.reshape( [o.f() for o in object_array.flat], object_array.shape ) 

我的情况类似于让 object_array[i,j] 成为 scipy.stats.norm 的一个实例,其中分布的参数对于不同的元素是不同的. scipy.stats.norm.rvs() 是我要调用的 f()。请注意,object_array 的大小可能非常大(最大约 1000x1000),所以我担心这是次优的,因为我在调用时至少制作了一份结果副本 reshape 。

请您参考如下方法:

您的做法似乎很合理。我使用 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