Python 中的 += 是什么意思? [英] What does += mean in Python?

查看:106
本文介绍了Python 中的 += 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 if cnt >0 和 len(aStr) >1:而 cnt >0:aStr = aStr[1:]+aStr[0]cnt += 1

+= 是什么意思?

解决方案

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

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

  • a = a + b中,a被求值两次.

  • Python:简单语句

    • 一个简单的语句包含在一个逻辑行中.

如果这是您第一次遇到 += 运算符,您可能想知道为什么它可以就地修改对象而不是构建新对象很重要.下面是一个例子:

# 两个变量引用同一个列表>>>列表 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 or dict, but int and str are immutable).

  • In a = a + b, a is evaluated twice.

  • Python: Simple Statements

    • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆