6

I am currently getting:

y=[[ 0.16666667]
[-0.16666667]
[ 0.16666667]]

This comes out of a function im using and i need to turn the above into a list in the format below:

x= [0.16666667,-0.16666667,0.16666667]

I tried list(y) but this does not work, because it returns:

[array([ 0.16666667]), array([-0.16666667]), array([ 0.16666667])]

How exactly would I do this??

user1819717
  • 133
  • 4

3 Answers3

6
my_list = [col for row in matrix for col in row]
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
  • @user1819717 don't forget to accept the answer if it was useful. – Trufa Dec 19 '12 at 03:03
  • The interpretation of multiple levels of iteration inside a generator expression or list comprehension is something which often confuses people and should thus be used with great care; once you get to the `for` statement, they are handled *left-to-right* rather than the more-obvious-to-me-and-several-other-people-that-I-have-spoken-to-on-the-matter inwards-from-the-right. Although I knew about that, I actually just a few days ago [got caught on it with assignment statements](http://stackoverflow.com/questions/13945048)... they work left-to-right too. – Chris Morgan Dec 19 '12 at 03:27
4

You can use the numpy .tolist() method:

array.tolist()

There is also one more advantage to it... It works with matrix objects, the list comprehension doesn't. If you want to remove the dimension first you can use numpy methods to do so, such as array.squeeze()

seberg
  • 8,785
  • 2
  • 31
  • 30
1

Grabs the first element from each sublist, using a list comprehension:

x = [elt[0] for elt in y]
Matt Ball
  • 354,903
  • 100
  • 647
  • 710