[英]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
:
list[:1] + np.vsplit(list[1], 3) + list[2:]
split
creates a list of arrays: split
创建一个数组列表:
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: 这在函数参数中很常见,例如func(*[alist])
,但在新的Python中,它在这样的列表中起作用:
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) (这在Python2中不起作用;列表联接更易于使用, [0] + [1,2,3] + [4]
,如@Psidom所示)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.