我在 Python 中看到这样的代码:
if cnt > 0 and len(aStr) > 1:
while cnt > 0:
aStr = aStr[1:]+aStr[0]
cnt += 1
什么是+=
mean?
a += b
本质上是一样的a = a + b
, 除了那个:
-
+
总是返回一个新分配的对象,但是+=
如果对象是可变的(例如,list
or dict
, but int
and str
是不可变的)。
-
In a = a + b
, a
被评估两次。
-
Python:简单语句 http://docs.python.org/reference/simple_stmts.html#augmented-assignment-statements
如果这是您第一次遇到+=
运算符,您可能想知道为什么它可以就地修改对象而不是构建新对象很重要。这是一个例子:
# 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], [])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)