Python3

时间:2017-10-05 17:05:18

标签: python python-3.x list numpy indices

我想绑定indices_listdata,如下所示。我发现此questionnumpy可能很有用。但就我而言,索引是嵌套的。我如何在下面实现?

indices_list = [
    [1,2],
    [0,2],
    [4]
]
data = [
    ['i', 'am', 'tom'],
    ['you', 'are', 'nice'],
    ['that', 'was', 'it'],
    ['yes', 'you', 'can'],
    ['no']
]

ideal: data[indices_list]
[
    [['you', 'are', 'nice'],
    ['that', 'was', 'it']],

    [['i', 'am', 'tom'],
    ['that', 'was', 'it']],

    [['no']]
]

更新

我找到了解决方案。也许,这是最好的..

bind_data = []
for indices in indices_list:
    tmp = []
    for ind in indices:
        tmp.append(data[ind])
    bind_data.append(tmp)
print(bind_data)
# [[['you', 'are', 'nice'], ['that', 'was', 'it']], [['i', 'am', 'tom'], ['that', 'was', 'it']], [['no']]]

1 个答案:

答案 0 :(得分:2)

[ [ data[j] for j in i ] for i in indices_list ]

输出:

[[['you', 'are', 'nice'], ['that', 'was', 'it']],
 [['i', 'am', 'tom'], ['that', 'was', 'it']],
 [['no']]]