Numpy:编写适用于1D和2D数组的函数的好方法是什么

2024-05-19 10:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数f(x),它执行以下操作:

  • 如果x是1D numpy数组,则返回g(x)
  • 返回np.数组(x(x)席席的G(Xi))如果x是2D麻木数组

实现这样的功能有什么好办法?

是否有一个numpy特定函数在一行中执行此操作,而不编写if语句?你知道吗


Tags: 函数功能numpyifnp数组语句办法
2条回答

ndim告诉您数组的维数,如:

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

从一维向量产生标量的函数g(x)可以扩展到任意高维,如下所示:

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 )

生产

3.0

[  3.  12.]

[[ 2.  2.]
 [ 2.  2.]
 [ 2.  2.]]

相关问题 更多 >

    热门问题