Liza
Liza

Reputation: 971

Converting list of Arrays to list of Lists?

After some complex operations, a resultant list is obtained, say list1, which is a list of different arrays.

Following is the list1

In [] : list1
Out [] : 
       [array([ 10.1]),
        array([ 13.26]),
        array([ 11.0 ,  12.5])]

Want to convert this list to simple list of lists and not arrays

Expected list2

      [ [ 10.1],
        [ 13.26],
        [ 11.0 ,  12.5] ]

Please let me know if anything is unclear.

Upvotes: 12

Views: 34359

Answers (6)

Abdelrahman Yosry
Abdelrahman Yosry

Reputation: 101

If you have more than 1D list, say 2D or more, you can use this to make all entries in just one list, I found it online but don't remember from whom did I take it xD

dummy = myList.tolist()
flatten = lambda lst: [lst] if type(lst) is int else reduce(add, [flatten(ele) for ele in lst])
points = flatten(dummy)

You will get a list of all points or all entries.

I have tested on this list

[[[3599, 532]], [[5005, 493]], [[4359, 2137]]]

and here is the output

[3599, 532, 5005, 493, 4359, 2137]

Upvotes: 0

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

new_list = list(map(list,old_list))

You can use the map function like above. You can see the result below:

In[12]: new_list = list(map(list,old_list))

In[13]: new_list

Out[13]: 
[[0.0],
 [0.0],
 [0.0, 0.5],
 [0.5],
 [0.5],
 [0.5, 0.68999999999999995],
 [0.68999999999999995, 0.88],
 [0.88],
 [0.88],
 [0.88],
 [0.88, 1.0],
 [1.0, 1.1000000000000001],
 [1.1000000000000001],
 [1.1000000000000001],
 [1.1000000000000001],
 [1.1000000000000001, 1.5],
 [1.5, 2.0],
 [2.0],
 [2.0]]

Upvotes: 2

user4312643
user4312643

Reputation:

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Upvotes: 1

miradulo
miradulo

Reputation: 29740

Just call ndarray.tolist() on each member array.

l = [arr.tolist() for arr in l]

This should be faster than building a NumPy array on the outer level and then calling .tolist().

Upvotes: 7

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6518

You can use tolist() in a list comprehension:

>>> [l.tolist() for l in list1]
[[0.0], [0.0], [0.0, 0.5], [0.5], [0.5], [0.5, 0.69], [0.69, 0.88], [0.88], [0.88], [0.88], [0.88, 1.0], [1.0, 1.1], [1.1], [1.1], [1.1], [1.1, 1.5], [1.5, 2.0], [2.0], [2.0]]

Upvotes: 13

Moses Koledoye
Moses Koledoye

Reputation: 78564

How about a simple list comprehension:

list1 = [list(x) for x in list1]

Upvotes: 3

Related Questions