【问题标题】:How to slice a np.array using a list of unknown length?如何使用未知长度的列表对 np.array 进行切片?
【发布时间】:2018-03-16 09:28:16
【问题描述】:

我可能使用了错误的名称/符号(SO 上可能存在答案,但我找不到)。请帮我澄清一下,以便我可以更新帖子,并在将来帮助像我这样的人。

我有一个未知维度n 的数组A,以及一个未知长度的索引列表l,其中l<=n

我希望能够选择与l 中的索引相对应的A 切片。即我想要:

A = np.zeros([3,4,5])
idx = [1,3]
B = # general command I am looking for

B_bad = A[idx] # shape = (2,4,5), not what I want!
B_manual = A[idx[0], idx[1]] # shape = (5), what I want, but as a general expression.
# it is okay that the indexes are in order i.e. 0, 1, 2, ...

【问题讨论】:

    标签: python arrays numpy slice


    【解决方案1】:

    你需要一个元组:

    >>> A[tuple(idx)]
    array([0., 0., 0., 0., 0.])
    >>> A[tuple(idx)].shape
    (5,)
    

    使用list 进行索引的含义不同。请参阅numpydocumentation on indexing 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2022-01-17
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      相关资源
      最近更新 更多