我想绑定indices_list
和data
,如下所示。我发现此question和numpy
可能很有用。但就我而言,索引是嵌套的。我如何在下面实现?
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']]]
答案 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']]]