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