Monica Monica - 9 months ago 22
Python Question

Converting arrays to lists

I got such a list of arrays:

[[array([ 0.00000000e+00, -1.00000000e+00, -6.12323400e-17]), array([ 0.00000000e+00, 1.00000000e+00, 6.12323400e-17]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])], [[0.9957649076694132, -0.09193611180665112, 0], array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])], [[0.012185959917421326, 0.60870153111176395, -0.0], array([ 0. , -0.47671475, -0. ]), array([-0.01218596, -0.13198678, 0. ]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])], [array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]), array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])]]


I am wondering how I might convert such a list to a list of lists.
I have tried to solve this problem by using a list of comprehension:

ves = [x.tolist() for x in j for j in ves]


However, I am getting an error in return:

TypeError: 'int' object is not iterable

Answer Source

I copied this object to an Ipython session. What I see is

a list of 4 items

In [246]: ll[0]
Out[246]: 
[array([  0.00000000e+00,  -1.00000000e+00,  -6.12323400e-17]),
 array([  0.00000000e+00,   1.00000000e+00,   6.12323400e-17]),
 array([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]),
 array([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])]

So this is 4 item list, with the elements being 1d and 2d arrays.

But ll[1] contains one list (of 3 items) and 3 2d arrays. ll[3] is 4 2d arrays.

To convert this to pure lists you will have to iterate down 2 levels, and apply tolist() to each element that is an array. And no conversion if the item is already a list.

I'd try to write it as a compound list comprehension; do I have to, and can you now take care of those details?


In [253]: [[l2.tolist() if isinstance(l2,np.ndarray) else l2 for l2 in l1] for l1 in ll]
Out[253]: 
[[[0.0, -1.0, -6.123234e-17],
  [0.0, 1.0, 6.123234e-17],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
 [[0.9957649076694132, -0.09193611180665112, 0],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
 [[0.012185959917421326, 0.608701531111764, -0.0],
  [0.0, -0.47671475, -0.0],
  [-0.01218596, -0.13198678, 0.0],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
 [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
  [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]]]