2010-10-26 41 views
1

我想实现一个类似的功能,并且想要接受一个数组或数字,我传递给numpy.onesnumpy零如何实现参数形状?

具体来说,我想这样做:

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]]]) 
+0

你能解释一下你越是想完成什么? – eumiro 2010-10-26 12:35:15

+0

我已更新该问题。 – 2010-10-26 12:37:04

+0

你给你的函数一个形状,你想添加一个维(2)并填充0.5? – eumiro 2010-10-26 12:40:52

回答

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]]) 
+0

我现在已经编辑它,并使形状可选,如您在评论中所述。所以你可以用'halfs()'来调用它,它将返回一个由2个0,5个元素组成的1维数组。 – eumiro 2010-10-26 13:02:54

+0

当shape是一个数组时,这看起来不错,但这不适用于int。 numpy如何接受数组或标量? – 2010-10-26 13:03:04

+0

@Neil,你必须用例子的输入和输出在你原来的问题中写一个例子。 – eumiro 2010-10-26 13:03:59