简体   繁体   中英

Get a list from numpy ndarray in Python?

I have a numpy.ndarray here which I am trying to convert it to a list.

>>> a=np.array([[[0.7]], [[0.3]], [[0.5]]])

I am using hstack for it. However, I am getting a list of a list. How can I get a list instead? I am expecting to get [0.7, 0.3, 0.5] .

>>> b = np.hstack(a)
>>> b
array([[0.7, 0.3, 0.5]])

Do you understand what you have?

In [46]: a=np.array([[[0.7]], [[0.3]], [[0.5]]])    
In [47]: a
Out[47]: 
array([[[0.7]],

       [[0.3]],

       [[0.5]]])    
In [48]: a.shape
Out[48]: (3, 1, 1)

That's a 3d array - count the []

You can convert it to 1d with:

In [49]: a.ravel()
Out[49]: array([0.7, 0.3, 0.5])

tolist converts the array to a list:

In [50]: a.ravel().tolist()
Out[50]: [0.7, 0.3, 0.5]

You could also use a[:,0,0] . If you use hstack , that partially flattens it - but not all the way to 1d.

In [51]: np.hstack(a)
Out[51]: array([[0.7, 0.3, 0.5]])
In [52]: _.shape
Out[52]: (1, 3)
In [53]: np.hstack(a)[0]
Out[53]: array([0.7, 0.3, 0.5])

Alternatively, numpy.ndarray.flatten can be used:

a.flatten().tolist()

And yet another possibility:

a.reshape(-1).tolist()

Output:

[0.7, 0.3, 0.5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM