Heinz - 7 months ago 42

Python Question

I got a list:

`rs = list([[(0, 167, 159, 0), (1, 168, 160, 1)], [(0, 167, 159, 1), (1, 168, 160, 0)]])`

and I want to arrange it into numpy array in matrix form, thus I wrote the following code:

`import numpy`

rs = list([[(0, 167, 159, 0), (1, 168, 160, 1)], [(0, 167, 159, 1), (1, 168, 160, 0)]])

k = 2

j = 0

h = 0

ars = []

element = list(rs)

ck_dist_m = numpy.array([[]], ndmin = 2)

while j <= k - 1:

while h <= k - 1:

rp = numpy.array(element[j][h][3], ndmin = 2)

ars.append(rp)

h = h + 1

else:

h = 0

ck_dist_m = numpy.vstack(ars)

j = j + 1

print ck_dist_m

I want the result to be:

`[[0, 1],`

[1, 0]]

But the script above gave this:

`[[0]`

[1]

[1]

[0]]

How to edit the script to get result in matrix form?

Answer

In the while loop I extract the third element in the sublist, and try to store them in matrix form.

Here is a much more direct way to achieve this:

```
>>> numpy.array(rs)[:,:,3]
array([[0, 1],
[1, 0]])
```