Naf*_*ffi 22 python performance merge list
鉴于,
list_1 = [1,2,3,4]
list_2 = [5,6,7,8]
Run Code Online (Sandbox Code Playgroud)
在python中实现以下功能的最快方法是什么?
list = [1,2,3,4,5,6,7,8]
Run Code Online (Sandbox Code Playgroud)
请注意,可以有很多方法在python中合并两个列表.我正在寻找最有效率的方式.
[编辑] ++++++++++++++++++++++++++++++++++++++++++++ [编辑]
感谢所有的答案.得到你的想法,我尝试了以下,这是我的理解.
码
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
Run Code Online (Sandbox Code Playgroud)
OUTPUT
19999999
0.125061035156
19999999
1.02858018875
19999999
0.03928399086
Run Code Online (Sandbox Code Playgroud)
所以,如果有人不打算在问题中重复使用list_1/list_2,那么延伸就是要走的路.另一方面,"+"是最快的方式.
我不确定其他选择.
再次感谢 :-)
pha*_*t0m 23
你可以使用串联:
list = list_1 + list_2
Run Code Online (Sandbox Code Playgroud)
如果你不需要保留list_1,你可以修改它:
list_1.extend(list_2)
Run Code Online (Sandbox Code Playgroud)
Moh*_*nki 11
如果您使用的是 python 3,还有一种方法可以做到这一点,而且速度要快一些(仅在 python 3.7 上测试)
[*list1, *list2]
Run Code Online (Sandbox Code Playgroud)
基准
from timeit import timeit
x = list(range(10000))
y = list(x)
def one():
x + y
def two():
[*x, *y]
print(timeit(one, number=1000, globals={'x':x, 'y': y}))
print(timeit(two, number=1000, globals={'x':x, 'y': y}))
0.10456193100253586
0.09631731400440913
Run Code Online (Sandbox Code Playgroud)
Suk*_*lra 10
list_1 + list_2可以.示例 -
>>> list_1 = [1,2,3,4]
>>> list_2 = [5,6,7,8]
>>> list_1 + list_2
[1, 2, 3, 4, 5, 6, 7, 8]
Run Code Online (Sandbox Code Playgroud)
小智 8
我测试了几种合并两个列表的方法(见下文),并在每次运行几次后得出以下顺序以规范缓存更改(大约有 15% 的差异)。
import time
c = list(range(1,10000000))
c_n = list(range(10000000, 20000000))
start = time.time()
*insert method here*
print (time.time()-start)
Run Code Online (Sandbox Code Playgroud)
方法一: c.extend(c_n)
方法二: c += c_n
方法三: c = c + c_n
方法四: c = [*c, *c_n]
结论
使用+=或.extend()如果您想就地合并。它们的速度要快得多。