^=, -= and += symbols in Python

我怕爱的太早我们不能终老 提交于 2021-02-05 18:56:28

问题


I am quite experienced with Python, but recently, when I was looking at the solutions for the codility sample tests I encountered the operators -=, +=, ^= and I am unable to figure out what they do. Perhaps could anyone explain the context in which they are used?


回答1:


As almost any modern language, python has Assignment Operators so they can use them every time you want to assign a value to a variable after doing some arithmetic or logical operation, both (assignment and operation)are expressed compact way in one statement....




回答2:


When you compute X = X + Y you are actually returning the sum of X and Y into a new variable, which, in your example, overwrites the previous value of X. When you use an assignment operator in the form of X += 1, the value 1 is directly summed on the current value of X, without returning the result in a new variable. Take a look at the code below:

>>> V = np.arange(10)
>>> view = V[3:]        # view is just a subspace (reference) of the V array
>>> print(V);print(view)
[0 1 2 3 4 5 6 7 8 9]
[3 4 5 6 7 8 9] 
>>> view = view + 3     # add view to a constant in a new variable 
>>> print(V);print(view)
[0 1 2 3 4 5 6 7 8 9]
[ 6  7  8  9 10 11 12]
>>> view = V[3:]
>>> view += 3           # here you actually modify the value of V
>>> print(V);print(view)
[ 0  1  2  6  7  8  9 10 11 12]
[ 6  7  8  9 10 11 12]

You can also look for the documentation of numpy.ndarray.base to check if an array is actually a reference of another array.



来源:https://stackoverflow.com/questions/37845445/and-symbols-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!