2016-09-20 127 views
3

編程切片我可以使用numpy.mgrid如下:NumPy的創建索引/從陣列

a = numpy.mgrid[x0:x1, y0:y1] # 2 dimensional 
b = numpy.mgrid[x0:x1, y0:y1, z0:z1] # 3 dimensional 

現在,我想以編程方式創建括號內的表達,因爲我不知道我是否有1,2 ,3個或更多維度。我正在尋找類似的東西:

shape = np.array([[x0, x1], [y0, y1], ... maybe more dimensions ...]) 
idx = (s[0]:s[1] for s in shape) 
a = numpy.mgrid[idx] 

這給了第二行至少一個語法錯誤。 如何正確生成這些索引/切片編程?(這裏的mgrid是一個示例/用例,這個問題實際上是關於索引的一般問題。)

+0

用'idx = [range(s [0],s [1])爲s形成]'然後使用'meshgrid':'np.meshgrid(* idx)'? – Divakar

回答

5

使用slice object。例如:

shape = np.array([[0, 10], [0, 10]]) 
idx = tuple(slice(s[0],s[1], 1) for s in shape) 
#yields the following 
#(slice(0, 10, 1), slice(0, 10, 1)) 
np.mgrid[idx] 

產生

array([[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
     [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
     [2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 
     [3, 3, 3, 3, 3, 3, 3, 3, 3, 3], 
     [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], 
     [5, 5, 5, 5, 5, 5, 5, 5, 5, 5], 
     [6, 6, 6, 6, 6, 6, 6, 6, 6, 6], 
     [7, 7, 7, 7, 7, 7, 7, 7, 7, 7], 
     [8, 8, 8, 8, 8, 8, 8, 8, 8, 8], 
     [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]], 

     [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]]) 

或者,可以使用numpy的速記np.s_,例如np.s_[0:10:1],而不是slice(1, 10, 1),但它們是等效的對象。

+1

'slice(s [0],s [1],None)'是意圖更好的翻譯 – Eric

+1

或甚至更好的slice(s [0],s [1])'。我認爲明確比隱含解釋更好。 – wflynny

+2

或者解包,'[切片(s,e)s,e形狀]' – hpaulj