Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?

前端 未结 3 566
悲哀的现实
悲哀的现实 2021-01-22 19:43

Let\'s say I want to implement Numpy\'s

x[:] += 1

in Cython. I could write

@cython.boundscheck(False)
@cython.wraparoundcheck(F         


        
3条回答
  •  灰色年华
    2021-01-22 20:39

    You could try using the flat attribute of the ndarray, which provides an iterator over the flattened array object. It always iterates in C-major ordering, with the last index varying the fastest. Something like:

    for i in range(x.size):
        x.flat[i] += 1
    

提交回复
热议问题