Reputation: 441
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.
Upvotes: 0
Views: 3119
Reputation: 231395
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, e.g. 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)
Upvotes: 2
Reputation: 214957
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:]
Upvotes: 2