# 从数组中选择特定元素Select specific elements from an array

``````  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]]
``````

``````  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)])
``````

## 4 个回复4

### ===============>>#1 票数：2

``````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]
``````

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

### ===============>>#2 票数：1

``````from itertools import chain, count, tee

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

### ===============>>#3 票数：1 已采纳

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

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

### ===============>>#4 票数：0

``````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)
``````

``````[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*']]
``````

3回复

1回复

4回复

2回复

3回复

3回复

4回复

4回复

3回复

1回复