【问题标题】:What does a [..., 0] mean in python array?[..., 0] 在 python 数组中是什么意思?
【发布时间】:2021-12-26 17:04:03
【问题描述】:

python数组中...的含义是什么? 下面的代码就是这样写的。

 obj = target[..., 0 ]

请帮帮我!

【问题讨论】:

标签: python arrays


【解决方案1】:

省略号扩展到所有其他维度。

来自numpy的documentation

省略号扩展为选择元组索引所有维度所需的 : 对象的数量。

3 维形状示例:

>>> x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
>>> x.shape
(2, 3, 1)
>>> x[...,0]
array([[1, 2, 3],
      [4, 5, 6]])

您可以看到第三维度的第一个项目是从所有其他项目中挑选出来的。由于它仅包含 1 项且不是切片,因此已展开。

【讨论】:

    【解决方案2】:

    在 numpy 数组中,省略号 (...) 等效于列 (:),因为它们允许数组切片,如下例所示,我创建了 2D numpy 数组并将其列打印为 1D 数组:

    import numpy as np
    
    x = np.array(range(12)).reshape(3,4)
    print(f'x = {x}')
    print(f'\nSlicing with ellipsis \t Slicing with column')
    for i in range(x.shape[1]):
        print(f'{x[...,i]} \t\t {x[:,i]}')
    

    这段代码的输出是:

    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]]
    
    Slicing with ellipsis    Slicing with column
    [0 4 8]                  [0 4 8]
    [1 5 9]                  [1 5 9]
    [ 2  6 10]               [ 2  6 10]
    [ 3  7 11]               [ 3  7 11]
    

    可以使用x[i,:] 或其等效的x[i,...] 对行执行相同的操作。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2015-03-20
    • 2020-01-07
    • 2013-05-28
    • 2018-09-10
    • 2022-12-01
    • 2019-12-08
    相关资源
    最近更新 更多