简体   繁体   English

将Python分配给第三个变量时为+ =

[英]+= in Python when assigning it to third variable

When I was looking at meaning of the += operator in Python, I looked at the answers to a similar question: What exactly does += do in python? 当我查看Python中+ =运算符的含义时,我看到了一个类似问题的答案: + =在python中到底做什么? . But in the below code excerpt: 但是在下面的代码摘录中:

increments += arr[i-1] - arr[i]

There is a third variable used. 使用了第三个变量。 If I understood the concept it subtracts arr[i] from arr[i-1] and adds it to increments 's value and the result is assigned to increments . 如果我理解该概念,它将从arr[i-1]减去arr[i]并将其添加到increments的值,并将结果分配给increments To elaborate: is the above statement similar to 详细说明:上面的陈述是否类似于

increments = increments + (arr[i-1] - arr[i])

or is there more to it? 还是还有更多?

From the documentation : 文档中

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. 扩充赋值评估目标(与普通赋值语句不同,不能解包)和表达式列表,对两个操作数执行特定于赋值类型的二进制运算,并将结果赋值给原始目标。 The target is only evaluated once. 该目标仅评估一次。

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. 可以将x += 1类的增强赋值表达式重写为x = x + 1以获得相似但不完全相等的效果。 In the augmented version, x is only evaluated once. 在增强版本中, x仅被评估一次。 Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. 同样,在可能的情况下,实际操作将在原地执行,这意味着不是创建新对象并将其分配给目标,而是修改了旧对象。

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. 与普通分配不同,扩充分配在评估右侧之前先评估左侧。 For example, a[i] += f(x) first looks-up a[i] , then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i] . 例如, a[i] += f(x)首先查找a[i] ,然后求值f(x)并执行加法,最后将结果写回到a[i]

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. 除了在单个语句中分配给元组和多个目标外,由扩展赋值语句完成的赋值与普通赋值的处理方式相同。 Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations. 类似地,除了可能的就地行为外,通过扩充分配执行的二进制操作与常规二进制操作相同。

For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments. 对于作为属性引用的目标,关于类和实例属性的警告同样适用于常规分配。

(my emphasis in the second paragraph) (我在第二段中强调)

So yes, there's more to it than just increments = increments + (arr[i-1] - arr[i]) . 因此,是的,它的意义不仅仅只是increments = increments + (arr[i-1] - arr[i]) The degree to which it matters depends on what you're applying the operator to. 重要的程度取决于您要应用运算符的对象。

To elaborate: is the above statement similar to 详细说明:上面的陈述是否类似于

increments = increments + (arr[i-1] - arr[i]) 增量=增量+(arr [i-1]-arr [i])

That depends on the type of "increments". 这取决于“增量”的类型。

With regards to the core built-in types (and other types that try to follow the pattern set by them) there are two at least two notable differences between + and +=. 关于核心内置类型(以及其他尝试遵循其设置的模式的类型),在+和+ =之间至少存在两个明显的区别。

  1. Where the type is mutable += performs the modification in-place while + creates a new object. 如果类型是可变的,则+ =就地执行修改,而+创建新对象。
  2. For lists += is more flexible than +, + will only accept another list but += will accept any iterable. 对于列表+ =比+更灵活,+仅接受另一个列表,而+ =将接受任何可迭代的列表。

Numbers are immutable, so for numbers the two statements behave the same. 数字是不可变的,因此对于数字,两个语句的行为相同。 However it is interesting to see if we can figure out some cases where they do behave differently. 但是,有趣的是,我们是否能够找出某些情况下它们的行为有所不同。

We are quite limited in what types we can use because relatively few types support both "+" and "-" and most types only support operations with the same type. 我们可以使用的类型非常有限,因为支持“ +”和“-”的类型相对较少,并且大多数类型仅支持相同类型的操作。 A combination of making increments a list and making the elements of arr sets is one way to demonstrate a difference. 使增量成为列表和使arr集的元素组合在一起是证明差异的一种方法。

increments=[]
i = 1 
arr=[{"foo","bar"},{"bar","baz"}]
increments += arr[i-1] - arr[i]
print(increments)

"Prints ['foo']" “打印['foo']”

increments=[]
i = 1 
arr=[{"foo","bar"},{"bar","baz"}]
increments = increments + (arr[i-1] - arr[i])
print(increments)

Raises an exception "TypeError: can only concatenate list (not "set") to list" 引发异常“ TypeError:只能将列表(而不是“ set”)连接到列表”

But that is a rather contrived example, for something more realistic we want a type that is mutable and supports both "+" and "-". 但这是一个相当人为的示例,对于更实际的事情,我们需要一个可变的类型并同时支持“ +”和“-”的类型。 I don't think there are any such types among the core built-in types but one widely used type that does is the "array" type from numpy. 我认为核心内置类型中没有任何此类类型,但是一种广泛使用的类型是numpy中的“数组”类型。

from numpy import array
increments=array((1,2))
oldincrements=increments
i = 1 
arr=[array((3,4)),array((5,6))]
increments += arr[i-1] - arr[i]
print(repr(oldincrements)+' '+repr(increments))

Prints "array([-1, 0]) array([-1, 0])". 打印“ array([-1,0])array([-1,0])”。 The numpy array was modified in-place so both "oldincrements" and "increments" were affected. numpy数组已就地修改,因此“ oldincrements”和“ increment”都受到影响。

from numpy import array
increments=array((1,2))
oldincrements=increments
i = 1 
arr=[array((3,4)),array((5,6))]
increments = increments + (arr[i-1] - arr[i])
print(repr(oldincrements)+' '+repr(increments))

Prints "array([1, 2]) array([-1, 0])" the array pointed to by increments was not modified in-place, instead a new array was created and assigned to "increments". 打印“ array([1,2])array([-1,0])”,增量所指向的数组未就地修改,而是创建了一个新数组并将其分配给“增量”。 So "oldincrements" was not affected. 因此,“旧增量”不受影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM