从已经为每个节编号的列表为np.split创建索引列表 [英] Create index list for np.split from the list that already has number for each section

查看:73
本文介绍了从已经为每个节编号的列表为np.split创建索引列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数字列表

list = [1,2,3,4,5,6,7,8,9]
number = [3,2,1,3]

我想从number

index = [3,5,6,9]

对于

np.split(list, index)

预期结果

[[1,2,3],[4,5],[6],[7,8,9]]

我尝试了类似newlist = [x+number[0:index(x)] for x in list]的方法,但仍然无法正常工作

I tried something like newlist = [x+number[0:index(x)] for x in list] but it still does not work

推荐答案

方法1

如果我们要使用 np.split 产生一个数组列表,我们需要在那些 indexes 上使用np.cumsum来为我们提供索引,以便在其中我们需要分割输入列表-

If we want to use np.split resulting in a list of arrays, we need to use np.cumsum on those indexes to give us indices where we need to split the input list -

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


方法2

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

To have a list of lists, another approach with a loop comprehension again using cumsum -

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

样品运行-

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

这篇关于从已经为每个节编号的列表为np.split创建索引列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆