【问题标题】:Efficient way to index a list with a numpy bool array in Python在 Python 中使用 numpy bool 数组索引列表的有效方法
【发布时间】:2017-02-06 09:40:09
【问题描述】:

如标题所示,索引 list l(n,) 布尔值 ndarray arlen(l) == ar.shape[0] 的最有效方法是什么?

【问题讨论】:

  • 除非ar 非常稀疏,否则我怀疑你能比先转换为数组更快np.array(l)[ar]
  • 你可以自己计时。看看timeit。答案可能会因列表的大小而异。

标签: python list numpy


【解决方案1】:

好的,让我们列出您可以尝试的习语。给它们计时,你必须自己做,因为这取决于ar 的大小和稀疏性,参见。 @Imanol Luengo 的评论

np.array(l)[ar] # output is an array
[e for e,m in zip(l, ar) if m]
[l[i] for i in np.where(ar)[0]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多