【问题标题】:Indices list access in Python3Python3 中的索引列表访问
【发布时间】:2018-03-17 09:38:38
【问题描述】:

我想绑定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']]]

【问题讨论】:

  • 字典呢?

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


【解决方案1】:
[ [ data[j] for j in i ] for i in indices_list ]

输出:

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

【讨论】:

  • 很好,这应该是最好的。
猜你喜欢
  • 2013-09-04
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 2015-05-13
  • 2018-07-05
相关资源
最近更新 更多