2013-04-16 53 views
2

選擇特定元素我有一個數組:從一個數組

X = [[5*, 0,  0,  0,  0,  0,  0,  0], 
     [9*, 6,  0,  0,  0,  0,  0,  0], 
     [4, 6*, 8,  0,  0,  0,  0,  0], 
     [0, 7*, 1,  5,  0,  0,  0,  0], 
     [9, 3,  3*,  4,  4,  0,  0,  0], 
     [4, 5,  5*,  6,  7,  5,  0,  0], 
     [4, 5,  6,  8*,  7,  7,  8,  0], 
     [4, 7,  8,  9*,  7,  3,  9,  6]] 

我想選擇和追加所有被*標記的值。該方法基本上是從第0行和第1行中選擇第0個元素,從第2行和第3行中選擇第1個元素。依此類推。

的結果集應該是:

Result = ((X[0][0], (X[1][0]), (X[2][1], X[3][1]), (X[4][2], X[5][2]), (X[6][3], X[7][3])) 

其可寫爲:

Result = ((X[n+0][n], (X[n+1][n]), (X[n+2][n+1], X[n+3][n+1]), (X[n+4][n+2], X[n+5][n+2]), (X[n+6][n+3], X[n+7][n+3])) 

    Where n = 0 

我該怎麼辦呢?我已經申請了這個,但它不工作:

Result = [] 

for a in X: 
    Result.append([[[ a[i][j] ] for i in range(0,8)] for j in range(0,8)]) 

但沒有結果。任何猜測?

+0

你或許應該移動到numpy的... – wim

回答

1

這將工作,如果X有一個甚至在它的多個列表:

>>> [(X[2*i][i], X[2*i+1][i]) for i in range(len(X)//2)] 
[(5, 9), (6, 7), (3, 5), (8, 9)] 

如果你不介意的扁平的名單,然後再會爲X工作任何長度:

>>> [lst[idx//2] for idx, lst in enumerate(X)] 
[5, 9, 6, 7, 3, 5, 8, 9] 
1

試試這個:

from itertools import chain, count, tee 

lst = [row[i] for row, i in zip(array, chain.from_iterable(zip(*tee(count(), 2))))] 
2

由於numpy標籤,我想我會廣告d這樣的:

import numpy as np 
X = np.array([[5 , 0,  0,  0,  0,  0,  0,  0], 
       [9 , 6,  0,  0,  0,  0,  0,  0], 
       [4, 6 , 8,  0,  0,  0,  0,  0], 
       [0, 7 , 1,  5,  0,  0,  0,  0], 
       [9, 3,  3 ,  4,  4,  0,  0,  0], 
       [4, 5,  5 ,  6,  7,  5,  0,  0], 
       [4, 5,  6,  8 ,  7,  7,  8,  0], 
       [4, 7,  8,  9 ,  7,  3,  9,  6]]) 
i = np.array([0, 1, 2, 3, 4, 5, 6, 7]) 
j = np.array([0, 0, 1, 1, 2, 2, 3, 3]) 

result = X[i, j] 
print result 
# [5 9 6 7 3 5 8 9] 

要產生我和你可以不喜歡的一般方案J:

n = 8 
i = np.arange(n) 
j = np.arange(n) // 2 
+0

你確定最後一行是正確的?在我的NumPy版本(1.5.1)中,「repeat」需要兩個參數。那也應該是''arange''? – Blair

+0

@Blair,的確應該是'arange',我已經修好了。 –

0

在numpy的:

import numpy as np 
x = [['5*','0 ','0 ','0 ','0 ','0 ','0 ','0 '], 
    ['9*','6 ','0 ','0 ','0 ','0 ','0 ','0 '], 
    ['4 ','6*','8 ','0 ','0 ','0 ','0 ','0 '], 
    ['0 ','7*','1 ','5 ','0 ','0 ','0 ','0 '], 
    ['9 ','3 ','3*','4 ','4 ','0 ','0 ','0 '], 
    ['4 ','5 ','5*','6 ','7 ','5 ','0 ','0 '], 
    ['4 ','5 ','6 ','8*','7 ','7 ','8 ','0 '], 
    ['4 ','7 ','8 ','9*','7 ','3 ','9 ','6 ']] 

a=np.array(x) 

然後做一個列表理解和/或Numpy切片得到的項目:

[a[i:,j][:2].tolist() for i,j in zip(range(0,7,2),range(0,7,1))] 

[a[i*2:,i][:2].tolist() for i in range(len(a)//2)] 

a[range(len(a)),np.repeat(range(len(a)//2),2)].reshape(4,2).tolist() 

任何情況下,輸出是:

[['5*', '9*'], ['6*', '7*'], ['3*', '5*'], ['8*', '9*']]