Difference between a -= b and a = a - b in Python

前端 未结 3 2011
攒了一身酷
攒了一身酷 2021-01-30 10:03

I have recently applied this solution for averaging every N rows of matrix. Although the solution works in general I had problems when applied to a 7x1 array. I have noticed tha

3条回答
  •  梦谈多话
    2021-01-30 10:38

    The docs say :

    The idea behind augmented assignment in Python is that it isn't just an easier way to write the common practice of storing the result of a binary operation in its left-hand operand, but also a way for the left-hand operand in question to know that it should operate `on itself', rather than creating a modified copy of itself.

    As a thumb rule, augmented substraction (x-=y) is x.__isub__(y), for IN-place operation IF possible, when normal substraction (x = x-y) is x=x.__sub__(y) . On non mutable objects like integers it's equivalent. But for mutable ones like arrays or lists, as in your example, they can be very different things.

提交回复
热议问题