连接两个列表-'+ ='和extend()之间的区别 [英] Concatenating two lists - difference between '+=' and extend()

查看:210
本文介绍了连接两个列表-'+ ='和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)

另一个使用plus(+)运算符:

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).

推荐答案

在字节码级别上的唯一区别是 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屋!

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