2013-10-21 27 views
0

我有一個列表A在python中包含一些數字,如[1,4,10]。我有另一個由10列和一些行組成的矩陣,第一列的數字就像[1 1 1 2 2 2 2 3 3 4 4 4 4 5 ....等等。現在我想從這個另一個數組中檢索那些行,其第一列由列表A中的數字組成。我如何在python中執行此操作?在Python中索引的問題

+1

你是什麼意思與 「陣列」(另一個列表,也許)?什麼是「專欄」?你的「數組」嵌套?請顯示一些代碼。 – Hyperboreus

+0

@Hyperboreus。我已經更新了這個問題。我在原版中犯了一個錯誤。我應該說矩陣, – user34790

+0

'matrix'不是Python中的內置類型。你在使用'numpy'庫嗎?或者你只是有一個列表清單,如'[[1,2],[3,4]]? – DSM

回答

0

如果您的意思是m[x + y * width]中的矩陣,那麼您可以使用切片檢索行X

例如:

row_index = 5 
column_count = 10 
start = row_index * column_count 
end = start + column_count 
row = m[start:end] 

,從而做自己想做的

rows = [] 
for index in list_A: 
    rows.append(list_A[index * 10:index * 10 + 10]) 

如果你正在談論檢索欄目,然後是這樣的

columns = [] 
for index in list_A: 
    columns.append(list_A[index:len(list_A):10]) 
1

這個怎麼樣:

target_list = [1, 4, 10] 

a = np.array([[1,0], 
       [5,0], 
       [10,0], 
       [4,0], 
       [1,0], 
       [7,0]]) 

first_col = a[:,0] 

# create a boolean array 
to_retrieve = np.in1d(first_col, target_list) 

result = a[to_retrieve] 

結果:

>>> result # retrieved rows whose first column elements are in the target list 
array([[ 1, 0], 
     [10, 0], 
     [ 4, 0], 
     [ 1, 0]])