简体   繁体   中英

python: how to remove brackets of a nested list within a list

I have a list of different arrays of different sizes

list = [array1,array2,array3,array4,array5]

now i want to use split function to split one of the array

newlist = [array1, np.vsplit(array2,3), array3,array4,array5]

to make a new list

newlist = [array1,array21,array22,array23,array3,array4,array5]

HOWEVER, what I got is always containing a list inside the newlist

newlist = [array1,[array21,array22,array23],array3,array4,array5]

how can i remove the brackets and generate what i want?

I believe there should be a very simple solution, but i have tried searching and couldn't get a answer.

You can directly add lists up by wrapping the remaining elements in separate lists first:

[array1] + np.vsplit(array2,3) + [array3, array4, array5]

or better you can slice the list :

list[:1] + np.vsplit(list[1], 3) + list[2:]

split creates a list of arrays:

In [115]: np.split(np.arange(10),2)
Out[115]: [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])]

When you make a new list containing arrays plus such a list, you get a list within a list. That's just normal list operations:

In [116]: [np.arange(3),np.split(np.arange(10),2),np.array([3,2])]
Out[116]: 
[array([0, 1, 2]),
 [array([0, 1, 2, 3, 4]), array([5, 6, 7, 8, 9])],
 array([3, 2])]

There are various ways of flattening or expanding such a nested list. One is the * operator. It's common in function arguments, eg func(*[alist]) , but in new Pythons works in a list like this:

In [117]: [np.arange(3),*np.split(np.arange(10),2),np.array([3,2])]
Out[117]: 
[array([0, 1, 2]),
 array([0, 1, 2, 3, 4]),
 array([5, 6, 7, 8, 9]),
 array([3, 2])]

Simple list example:

In [118]: [1, [2,3,4], 5]
Out[118]: [1, [2, 3, 4], 5]
In [119]: [1, *[2,3,4], 5]
Out[119]: [1, 2, 3, 4, 5]

(This doesn't work in Python2; There a list join is easier to use, [0] + [1,2,3] + [4] , as @Psidom shows)

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