def f(x):
if np.ndim(x) == 1:
return g(x)
elif np.ndim(x) == 2:
return np.array([g(xi) for xi in x])
else:
# Whatever you want to do with more than 2 directions
return None
import numpy as np
def myfunc(x):
return sum(x)
def f( g, x ):
if len(x.shape) == 1:
return g(x)
if len(x.shape) > 1:
return np.array( [f(g,v) for v in x] )
# Test with one dimensional input
res = f( myfunc, np.array( [0.,1.,2.] ) )
print( res )
# Test with two dimensional input
res = f( myfunc, np.array( [[0.,1.,2.],[3.,4.,5.]] ) )
print( res )
# And, still more dimensions
res = f( myfunc, np.ones( (3,2,2) ) )
print( res )
ndim
告诉您数组的维数,如:从一维向量产生标量的函数g(x)可以扩展到任意高维,如下所示:
生产
相关问题 更多 >
编程相关推荐