2016-11-20 154 views
0

下面的代碼正確地適用於下面描述的特定情況。我想概括它。我正在嘗試打印出陣列的子陣列。打印陣列的子陣列

import numpy as np 

alpha = input("input this number... ") 
X = np.arange(alpha**2).reshape(alpha,alpha) #square matrix 

beta = input("a number in the matrix X") 

if(beta > alpha**2): 
    print("must pick number inside array"), exit() 

print(X) #correct square matrix 

00 01 02 03 04 
05 06 07 08 09 
10 11 12 13 14 
15 16 17 18 19 
20 21 22 23 24 

我想打印這個矩陣X的3×3子陣列,獨立的我選擇的α爲(獨立的3×3方形或5×5正方形矩陣等)。如下所示。

回答

1

如果陣列中的所有值都是唯一的(因爲它們是在這兩個例子中你的問題):

​​

這個代碼是找到在2D (i, j)指數數組,使X[i,j]等於beta的值。因此X[i-1:i+2,j-1:j+2]是3x3數組,其中beta值在中心,除非beta位於矩陣的邊緣。

要獲得所有可用值甚至在邊緣:

print(X[max(i-1,0):i+2,max(j-1,0):j+2]) 
+0

@Integrals有什麼優勢?它是'i == 0或j == 0或i ==(alpha-1)或j ==(alpha-1)'。 – jfs

+0

@Integrals這是非常基本的。答案中的代碼顯示如何獲取(i,j)索引。在我以前的評論中的顯式條件顯示瞭如何找出beta是否在邊緣(通過檢查它的下標:i,j)。如果你不明白我的評論;問一個單獨的問題,關於如何檢測輸入值「beta」是否在方形numpy數組的邊緣。 – jfs

+0

@Integrals我的評論使用'或'條件之間的原則是:你不應該用逗號代替它。你應該閱讀一本關於Python的書(任何書)。這將節省您的時間,以避免陷入瑣碎的問題。有一個[Python標籤描述中的免費書籍列表](http://stackoverflow.com/tags/python/info) – jfs

1

你可以試試:

import numpy as np 

alpha = input("input this number... ") 
X = np.arange(alpha**2).reshape(alpha,alpha) #square matrix 

beta = input("a number in the matrix X") 
if(beta > alpha**2): 
    print("must pick number inside array"), exit() 
row, col = beta // alpha, beta % alpha # This will give you the idxs of beta number in array 
subsize = input("a size of submatrix you want to get") 
border = (subsize - 1) // 2 

subrand = np.array(X)[row - border: row + border + 1, col - border: col + border + 1] 
print(subrand)