python 列表:附加 vs += [英] python list: append vs +=

查看:26
本文介绍了python 列表:附加 vs +=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 Python 列表,append()+= 是否相同?我知道 + 将导致创建一个新列表,而 append() 只是将新内容附加到旧列表中.但是 += 会被优化为更类似于 append() 吗?因为他们做同样的事情.

For Python list, is append() the same as +=? I know that + will lead to the creation of a new list, while append() just append new stuff to the old list. But will += be optimized to be more similar to append()? since they do the same thing.

推荐答案

这是一个 __iadd__ 操作符.文档.

重要的是,这意味着它只会尝试追加.例如,如果 x 是具有 __iadd__() 方法的类的实例,则 x += y 等价于 x = x.__iadd__(y) . 否则,会考虑 x.__add__(y)y.__radd__(x) ,与 x + y<的评估一样/code>."

Importantly, this means that it only tries to append. "For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y."

该线程专门处理列表及其 iadd 行为

这篇关于python 列表:附加 vs +=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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