简体   繁体   中英

How can I convert a numpy object to a regular python list?

I have a variable x that has a dtype of float32 , which contains:

[[0. .... 0.]
 [0. .... 0.]
 [0. .... 0.]
 [0. .... 0.]]

I have another variable y that has a dtype of object , which contains:

[array([0., ..., 0., 0.], dtype=float32)
 array([0., ..., 0., 0.], dtype=float32)
 array([0., ..., 0., 0.], dtype=float32)
 array([0., ..., 0., 0.], dtype=float32)]

That's after I do y = np.array(y)

I need to convert y to match the same type and structure of x . How can I accomplish this?

You can just stack the arrays:

y = np.stack(y)

If you want to convert to a list you can do:

y.tolist()

Note that this will also convert the Numpy data types ( np.float32 in your case) to Python internal data types ( float ).

Using a list comprehension should do it..

x = [np.array([1,2,3]),np.array([4,5,6])]
y = [list(i) for i in x]
print(y)

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