一个简单的语句包含在一个逻辑行中.如果这是您第一次遇到 += 运算符,您可能想知道为什么它可以就地修改对象而不是构建一个新对象很重要.下面是一个例子:# 两个变量引用同一个列表>>>列表 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 += 1What 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 or dict, but int and str are immutable).In a = a + b, a is evaluated twice.Python: Simple StatementsA 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 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-03 20:27