Converting a list with numpy arrays into lists in Python

Question:

I have a list B11 containing a list of numpy arrays. I want to convert each of these arrays into lists but I am getting an error. I also show the expected output.

import numpy as np

B11=[[np.array([353.856161,   0.      ,   0.      ]), 
      np.array([  0.      ,   0.      , 282.754301,   0.      ])], 
     [np.array([  0.      , 294.983702, 126.991664])]]

C11=B11.tolist()

The error is

in <module>
    C11=B11.tolist()

AttributeError: 'list' object has no attribute 'tolist'

The expected output is

[[[353.856161,   0.      ,   0.      ],[  0.      ,   0.      , 282.754301,   0.      ]],
 [  0.      , 294.983702, 126.991664]]
Asked By: jcbose123

||

Answers:

B11 is already a python list – its elements are numpy arrays.
You’re looking for something like C11 = [sublist.tolist() for sublist in B11].

This will traverse B11 and create a new list whose elements are constructed by calling the .tolist() method on each sublist from B11.

Answered By: Tomer Ariel
for x in B11:
    for y in x:
        print(y.tolist())

#output:

[353.856161, 0.0, 0.0]
[0.0, 0.0, 282.754301, 0.0]
[0.0, 294.983702, 126.991664]

Or List comprehension to keep the values:

[[y.tolist() for y in x] for x in B11]

#[[[353.856161, 0.0, 0.0], [0.0, 0.0, 282.754301, 0.0]],
#[[0.0, 294.983702, 126.991664]]]
Answered By: Talha Tayyab
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.