从数组中选择特定元素

时间:2013-04-16 03:57:36

标签: python numpy

我有一个数组:

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

但没有结果。任何猜测?

4 个答案:

答案 0 :(得分:2)

由于numpy标签,我想我会加上这个:

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]

要在一般情况下生成i和j,您可以执行以下操作:

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

答案 1 :(得分:1)

试试这个:

from itertools import chain, count, tee

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

答案 2 :(得分: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]

答案 3 :(得分: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*']]