简体   繁体   中英

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.

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

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() .

How about a simple list comprehension :

list1 = [list(x) for x in list1]
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]]

Use tolist() :

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

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]

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