This is my first post and I’m still a Python and Scipy newcomer, so go easy on me! I’m trying to convert an Nx1 matrix into a python list. Say I have some 3×1 matrix
x = scipy.matrix([1,2,3]).transpose()
My aim is to create a list, y, from x so that
y = [1, 2, 3]
I’ve tried using the tolist() method, but it returns [[1], [2], [3]], which isn’t the result that I’m after. The best i can do is this
y = [xi for xi in x.flat]
but it’s a bit cumbersome, and I’m not sure if there’s an easier way to achieve the same result. Like I said, I’m still coming to grips with Python and Scipy…
Thanks
A question for your question
While Sven and Navi have answered your question on how to convert
into a list, I’ll ask a question before answering:
Using array instead of matrix
If you look at the Numpy for Matlab Users wiki/documentation page, section 3 discusses ‘array’ or ‘matrix’? Which should I use?. The short answer is that you should use array.
One of the advantages of using an array is that:
Also, as stated in the Numpy Reference Documentation, "Matrix objects are always two-dimensional." This is why
x.tolist()returned a nested list of[[1], [2], [3]]for you.Since you want an Nx1 object, I’d recommend using array as follows:
If you really want to use matrix
If for some reason you truly need/want to use a matrix instead of an array, here’s what I would do:
In words, the
x.T.tolist()[0]will:.Tattribute.tolist()[0]