连接两个列表 - '+=' 和 extend() 之间的区别 [英] Concatenating two lists - difference between '+=' and extend()
问题描述
我已经看到实际上有两种(可能更多)在 Python 中连接列表的方法:一种方法是使用 extend() 方法:
I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method:
a = [1, 2]
b = [2, 3]
b.extend(a)
另一个使用加号(+)运算符:
the other to use the plus(+) operator:
b += a
现在我想知道:这两个选项中的哪一个是进行列表连接的pythonic"方式,两者之间是否有区别(我查阅了官方 Python 教程,但找不到任何关于此主题的信息).
Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is there a difference between the two (I've looked up the official Python tutorial but couldn't find anything anything about this topic).
推荐答案
字节码级别的唯一区别是 .extend
方式涉及到函数调用,这在 Python 中比 INPLACE_ADD
.
The only difference on a bytecode level is that the .extend
way involves a function call, which is slightly more expensive in Python than the INPLACE_ADD
.
除非您执行此操作数十亿次,否则您无需担心.然而,瓶颈很可能位于其他地方.
It's really nothing you should be worrying about, unless you're performing this operation billions of times. It is likely, however, that the bottleneck would lie some place else.
这篇关于连接两个列表 - '+=' 和 extend() 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!