简体   繁体   中英

Python - Apply function over pairwise elements of array without using loops

Suppose I want to apply a function func over the pairwise elements of a numpy array A, and I want to produce an a new matrix M, where M[i,j] = func(A[i],A[j]) . Is there someway to do this in Python without using loops?

Yes, simply something like this (assuming your func is a nice numpy friendly function):

A = np.arange(5)

def f(x,y):
    return x+2*y

X,Y = np.meshgrid(A,A)

M = f(X,Y)

If not numpy friendly you may want to look at np.vectorize .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM