Python 中的 ^=、-= 和 += 符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37845445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
^=, -= and += symbols in Python
提问by Mc Tor
I'm quite experienced with Python
, but recently trying the sample tests of codility
and looked at the solutions. I have encountered -=
, +=
, ^=
and I am unable to figure out what they do. Perhaps could anyone explain the context in which they are used?
我对 非常有经验Python
,但最近尝试了 的示例测试codility
并查看了解决方案。我遇到了-=
, +=
,^=
我无法弄清楚它们是做什么的。也许任何人都可以解释使用它们的上下文?
Thanks!
谢谢!
回答by ΦXoc? ? Пepeúpa ツ
As almost any modern language, python has Assignment Operatorsso 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....
与几乎所有现代语言一样,python 具有赋值运算符,因此它们可以在每次您想在执行一些算术或逻辑运算后为变量赋值时使用它们,(赋值和运算)都在一个语句中以紧凑的方式表达...... .
回答by Oliari
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:
当您计算 X = X + Y 时,您实际上是将 X 和 Y 的总和返回到一个新变量中,在您的示例中,它会覆盖 X 的先前值。当您使用 X += 1 形式的赋值运算符时,值 1 直接对 X 的当前值求和,而不在新变量中返回结果。看看下面的代码:
>>>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.
您还可以查找 numpy.ndarray.base 的文档以检查数组是否实际上是另一个数组的引用。
I hope it helps
我希望它有帮助