如何在不连接的情况下索引 python 列表列表



>假设我有这样的输入:

bl = [[0,1,2,3,4,5], [6,7,8,9], [10,11,12,13]]
idx = [10, 6, 3, 4, 9, 2]

我希望输出是这样的:

out = [[3,4,2], [6,9], [10]]

背后的逻辑是这样的:

首先,我可以将lb_cat视为一些串联版本:

lb_cat = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]

然后从串联列表中索引:

pick = lb_cat[idx] = [10, 6, 3, 4, 9, 2]

最后,将拾取的元素分配回每个组以获得

 out = [[3,4,2], [6,9], [10]]

困难在于我不能使用像连接这样的操作,因为我的输入不是标准的python列表,它不支持串联操作。

我想做的是从"串联"视图中使用索引的对象列表中进行选择,但我实际上从列表的每个元素中进行选择lb

我怎样才能以有效的python方式做到这一点?

=======

=
===编辑:

我已经实现了一个慢速版本,如下所示:

import numpy as np
bl = [[0,1,2,3,4,5], [6,7,8,9], [10,11,12,13]]
idx = [10, 6, 3, 4, 9, 2]
milestones = np.cumsum(np.array([len(el) for el in bl])).tolist()
milestones = [0,] + milestones
res = [[] for _ in bl]
for ix in idx:
    for i, m in enumerate(milestones):
        if ix < m:
            res[i-1].append(ix)
            break

这对我有用,但太慢了。我有办法让它更快吗?

我不确定我是否正确理解了您的问题,但我希望这将作为一个足够的答案。

x=0   //to count the total number of numbers with concatination
out = []   //to store final result
for i in bl:
    temp = []
    for j in i:
        if x in idx:     //to check if you want xth indexed element
            temp.append(j)
        x+=1
    if len(temp)>0:      //only append if has an index in idx, i am not sure if you want this
        out.append(temp)
print(out)    //to print final output

最新更新