python 列表:附加 vs += [英] python list: append 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
."
这篇关于python 列表:附加 vs +=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!