python - += 在 Python 中是什么意思?

标签 python syntax

我在 Python 中看到这样的代码:

    if cnt > 0 and len(aStr) > 1:
        while cnt > 0:                  
            aStr = aStr[1:]+aStr[0]
            cnt += 1

+= 是什么意思?

最佳答案

a += b 本质上与 a = a + b 相同,除了:

  • + 总是返回一个新分配的对象,但是 += 应该(但不必)就地修改对象,如果它是可变的(例如 listdict,但 intstr 是不可变的)。

  • a = a + b中,a被计算了两次。

  • Python: Simple 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], [])

关于python - += 在 Python 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/823561/

相关文章:

python - 无法为自定义项目安装依赖项

python - 为什么使用列表时用 numba 计算总和会变慢?

python - * : 'NoneType' and 'NoneType' (Python) 不支持的操作数类型

sql - 当 JOIN 列在两个表中具有相同名称时,T-SQL 语法缩写?

r - data.table 语法遇到一些问题

c - C 中箭头运算符 (->) 的用法

python - 在Python中给定一个包含该子字符串的字符串,查找该子字符串的所有索引

python - Generic[T] 基类 - 如何从实例中获取 T 的类型?

python - 我的代码显示了不正确的mysql语法,尽管它是正确的

regex - 描述正则表达式的上下文无关语法?