Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为np.split创建索引列表,该列表已包含每个节的编号_Python_Numpy - Fatal编程技术网

Python 为np.split创建索引列表,该列表已包含每个节的编号

Python 为np.split创建索引列表,该列表已包含每个节的编号,python,numpy,Python,Numpy,我有两张号码表 list = [1,2,3,4,5,6,7,8,9] number = [3,2,1,3] 我想为np.split创建索引,从number index = [3,5,6,9] 为了 预期结果 [[1,2,3],[4,5],[6],[7,8,9]] 我尝试了类似于newlist=[x+number[0:index(x)]的方法,用于列表中的x],但仍然不起作用 如果我们想使用结果来生成数组列表,我们需要在这些索引上使用np.cumsum,为我们提供需要拆分输入列表的索引- n

我有两张号码表

list = [1,2,3,4,5,6,7,8,9]
number = [3,2,1,3]
我想为np.split创建索引,从
number

index = [3,5,6,9]
为了

预期结果

[[1,2,3],[4,5],[6],[7,8,9]]
我尝试了类似于
newlist=[x+number[0:index(x)]的方法,用于列表中的x]
,但仍然不起作用

如果我们想使用结果来生成数组列表,我们需要在这些索引上使用
np.cumsum
,为我们提供需要拆分输入列表的索引-

np.split(list1, np.cumsum(number)[:-1])
样本运行-

In [36]: list1 = [1,2,3,4,5,6,7,8,9]
    ...: number = [3,2,1,3]
    ...: 

In [37]: np.split(list1, np.cumsum(number)[:-1])
Out[37]: [array([1, 2, 3]), array([4, 5]), array([6]), array([7, 8, 9])]
In [45]: idx = np.r_[0,np.cumsum(number)]

In [46]: [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
Out[46]: [[1, 2, 3], [4, 5], [6], [7, 8, 9]]

方法#2

要获得列表列表,另一种方法是使用
cumsum
-

idx = np.r_[0,np.cumsum(number)]
out = [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
样本运行-

In [36]: list1 = [1,2,3,4,5,6,7,8,9]
    ...: number = [3,2,1,3]
    ...: 

In [37]: np.split(list1, np.cumsum(number)[:-1])
Out[37]: [array([1, 2, 3]), array([4, 5]), array([6]), array([7, 8, 9])]
In [45]: idx = np.r_[0,np.cumsum(number)]

In [46]: [list1[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
Out[46]: [[1, 2, 3], [4, 5], [6], [7, 8, 9]]