Python 中的 += 是什么意思? [英] What does += mean in Python?
问题描述
我在 Python 中看到这样的代码:
if cnt >0 和 len(aStr) >1:而 cnt >0:aStr = aStr[1:]+aStr[0]cnt += 1
+=
是什么意思?
a += b
本质上与 a = a + b
相同,除了:
+
总是返回一个新分配的对象,但是+=
应该(但不必)就地修改对象,如果它是可变的(例如list
或dict
,但int
和str
是不可变的).在
a = a + b
中,a
被求值两次.- 一个简单的语句包含在一个逻辑行中.
如果这是您第一次遇到 +=
运算符,您可能想知道为什么它可以就地修改对象而不是构建新对象很重要.下面是一个例子:
# 两个变量引用同一个列表>>>列表 1 = []>>>列表 2 = 列表 1# += 修改list1和list2指向的对象>>>列表 1 += [0]>>>清单 1、清单 2([0], [0])# + 创建一个新的、独立的对象>>>列表 1 = []>>>列表 2 = 列表 1>>>列表 1 = 列表 1 + [0]>>>清单 1、清单 2([0], [])
I see code like this for example in Python:
if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
What does the +=
mean?
a += b
is essentially the same as a = a + b
, except that:
+
always returns a newly allocated object, but+=
should (but doesn't have to) modify the object in-place if it's mutable (e.g.list
ordict
, butint
andstr
are immutable).In
a = a + b
,a
is evaluated twice.-
- A simple statement is comprised within a single logical line.
If this is the first time you encounter the +=
operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:
# two variables referring to the same list
>>> list1 = []
>>> list2 = list1
# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])
# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])
这篇关于Python 中的 += 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!