在python中合并两个列表的最快方法是什么? [英] What is the fastest way to merge two lists in python?
问题描述
给出
list_1 = [1,2,3,4]
list_2 = [5,6,7,8]
在python中实现以下目标的最快方法是什么?
What is the fastest way to achieve the following in python?
list = [1,2,3,4,5,6,7,8]
请注意,有很多方法可以在python中合并两个列表.我正在寻找最省时的方法.
Please note that, there can be many ways to merge two lists in python. I am looking for the most time efficient way.
++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++
感谢所有答案.了解您的想法后,我尝试了以下操作,这是我的理解.
Thanks for all the answers. Getting your ideas, I tried the following and here is my understanding.
CODE
import time
c = list(range(1,10000000))
c_n = list(range(10000000, 20000000))
start = time.time()
c = c+c_n
print len(c)
print time.time() - start
c = list(range(1,10000000))
start = time.time()
for i in c_n:
c.append(i)
print len(c)
print time.time() - start
c = list(range(1,10000000))
start = time.time()
c.extend(c_n)
print len(c)
print time.time() - start
输出
19999999
0.125061035156
19999999
1.02858018875
19999999
0.03928399086
因此,如果某人不愿意在问题中重复使用list_1/list_2,则可以采用扩展的方式.另一方面,"+" 是最快的方法.
So, if someone does not bother reusing list_1/list_2 in the question then extend is the way to go. On the other hand, "+" is the fastest way.
我不确定其他选项.
再次感谢:-)
推荐答案
您可以使用串联:
list = list_1 + list_2
如果您不需要保留list_1,则可以对其进行修改:
If you don't need to keep list_1 around, you can just modify it:
list_1.extend(list_2)
这篇关于在python中合并两个列表的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!