-4

For example I have:

q1=[]
q2=[]
q3=[]

And after some operations they are:

q1 = [0, 1]
q2 = [2, 3, 4, 5, 6]
q3 = [7, 8, 9]

So I have 3 arrays. As you see they have different length. I want to make a matrix that will look like:

matrix = [[0, 1],
          [2, 3, 4, 5, 6],
          [7, 8, 9]]

And so for example matrix[1] will return [2, 3, 4, 5, 6]

How can I do this? I've tried some approaches like v = np.matrix([q1, q2, q3]) but it doesn't help

3 Answers3

1
import numpy as np
q1 = [0, 1]
q2 = [2, 3, 4, 5, 6]
q3 = [7, 8, 9]

V = np.array([q1, q2, q3])
print(V[0])

Hope it helps.

Sleeba Paul
  • 613
  • 1
  • 6
  • 14
1

There is no need to use numpy here. You can simply create a new list and add q1, q2, and q3 to it.

q = [q1, q2, q3]

print(q[1])

Output :

[2, 3, 4, 5, 6]
0

If you do not need np.matrix AT ANY PRICE then you could use np.array instead, following code:

import numpy as np
q1 = [0,1]
q2 = [2,3,4]
x = np.array([q1,q2])

I tested it and it works properly in numpy version 1.15.4. However keep in mind that x is array of dtype object. For discussion about irregular (non-rectangular/variable-length) arrays see this topic. Note also that documentation discourages usage of np.matrix.

Daweo
  • 31,313
  • 3
  • 12
  • 25