Home > Software design >  Converting a list with numpy arrays into lists in Python
Converting a list with numpy arrays into lists in Python

Time:01-02

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]]

CodePudding user response:

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]]]

CodePudding user response:

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.

  • Related