numpy零如何实现参数形状?

时间:2010-10-26 12:19:46

标签: python numpy

我想实现一个类似的函数,并希望接受我传递给numpy.ones的数组或数字。

具体来说,我想这样做:

def halfs(shape):
    shape = numpy.concatenate([2], shape)
    return 0.5 * numpy.ones(shape)

示例输入输出对:

# default
In [5]: beta_jeffreys()
Out[5]: array([-0.5, -0.5])

# scalar
In [5]: beta_jeffreys(3)
Out[3]: 
array([[-0.5, -0.5, -0.5],
       [-0.5, -0.5, -0.5]])

# vector (1)
In [3]: beta_jeffreys((3,))
Out[3]: 
array([[-0.5, -0.5, -0.5],
       [-0.5, -0.5, -0.5]])

# vector (2)
In [7]: beta_jeffreys((2,3))
Out[7]: 
array([[[-0.5, -0.5, -0.5],
        [-0.5, -0.5, -0.5]],

       [[-0.5, -0.5, -0.5],
        [-0.5, -0.5, -0.5]]])

1 个答案:

答案 0 :(得分:1)

def halfs(shape=()):
    if isinstance(shape, tuple):
        return 0.5 * numpy.ones((2,) + shape)
    else:
        return 0.5 * numpy.ones((2, shape))



a = numpy.arange(5)
# array([0, 1, 2, 3, 4])


halfs(a.shape)
#array([[ 0.5,  0.5,  0.5,  0.5,  0.5],
#       [ 0.5,  0.5,  0.5,  0.5,  0.5]])

halfs(3)
#array([[ 0.5,  0.5,  0.5],
#       [ 0.5,  0.5,  0.5]])