2010-10-26 40 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