【问题标题】:Iterating over the last dimensions of a numpy array迭代numpy数组的最后一个维度
【发布时间】:2019-04-26 23:54:32
【问题描述】:

考虑以下 sn-p:

a = np.ones((2,2,2,2,2))
for example in a:
    for row in example:
        for col in row:
            for box in col:
                print (box.shape)

有这么多嵌套的fors 会导致一些非常丑陋的代码。

如何仅通过一次显式迭代获得相同的效果?

【问题讨论】:

    标签: python arrays python-3.x numpy iteration


    【解决方案1】:

    重塑你的数组:

    for box in a.reshape(16,2):
        print(box.shape)
    

    一个通用的解决方案:

    for box in a.reshape(np.prod(a.shape[:-1]), a.shape[-1]):
         print(box.shape)
    

    它将始终遍历a的最后一个维度。

    【讨论】:

    • 在不引用 a 的形状的情况下,仅引用我们要迭代的轴的任何方式吗?
    • @Jsevillamol 查看我的更新以获得一般解决方案:)
    猜你喜欢
    • 2021-08-23
    • 2021-09-08
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2019-11-20
    • 2018-10-12
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多