What does [:, :] mean on NumPy arrays

前端 未结 3 1151
梦谈多话
梦谈多话 2020-12-13 00:12

Sorry for the stupid question. I\'m programming on PHP but found some nice code on Python and want to \"recreate\" it on PHP. But I\'m quite frustrated about the line

<
3条回答
  •  不知归路
    2020-12-13 01:10

    This is slice assignment. Technically, it calls1

    self.activity.__setitem__((slice(None,None,None),slice(None,None,None)),self.h)
    

    which sets all of the elements in self.activity to whatever value self.h is storing. The code you have there really seems redundant. As far as I can tell, you could remove the addition on the previous line, or simply use slice assignment:

    self.activity = numpy.zeros((512,512)) + self.h
    

    or

    self.activity = numpy.zeros((512,512))
    self.activity[:,:] = self.h
    

    Perhaps the fastest way to do this is to allocate an empty array and .fill it with the expected value:

    self.activity = numpy.empty((512,512))
    self.activity.fill(self.h)
    

    1Actually, __setslice__ is attempted before calling __setitem__, but __setslice__ is deprecated, and shouldn't be used in modern code unless you have a really good reason for it.

提交回复
热议问题