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

问题描述 投票:-1回答:1

假设我输入如下:

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

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

python numpy indexing slice
1个回答
0
投票

我不确定我是否理解你的问题,但我希望这可以作为一个充分的答案。

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
© www.soinside.com 2019 - 2024. All rights reserved.