【问题标题】:Iterating over numpy array keeping the indices迭代numpy数组保持索引
【发布时间】:2018-11-24 21:47:34
【问题描述】:

考虑下面的sn-p代码:

n_samples, n_rows, n_cols, n_boxes_per_cell, _ = Y_pred.shape
    for example in range(n_samples):
        for x_grid in range(n_rows):
            for y_grid in range(n_cols):
                for bnd_box in range(n_boxes_per_cell):
                    bnd_box_label = Y_pred[example, x_grid, y_grid, bnd_box]
                    do_some_stuff(bnd_box_label, x_grid, y_grid)

如何通过最多一次显式迭代获得功能等效的代码?请注意,我需要索引 x_gridy_grid

【问题讨论】:

    标签: python numpy iteration


    【解决方案1】:

    你可以使用np.ndindex:

    for example, x_grid, y_grid, bnd_box in np.ndindex(Y_pred.shape[:4]):
        etc.
    

    【讨论】:

      【解决方案2】:

      我不确定这是否是您要查找的内容,但您始终可以使用多个可迭代对象构建生成器:

      all_combinations = ((a, b, c, d) for a in range(n_samples)
                                       for b in range(n_rows) 
                                       for c in range(n_cols) 
                                       for d in range(n_boxes_per_cell))
      
      for examples, x_grid, y_grid, bnd_box in all_combinations:
          do stuff
      

      这与使用 itertools.product(*iterables) 相同,并且对任何可迭代对象都有效,而不仅仅是对索引/整数的迭代。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-29
        • 2017-06-24
        相关资源
        最近更新 更多