在python中合并两个列表的最快方法是什么?

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)

  • `未定义`?哪有这回事。`[] + ["a"] == ["a"]`。如果你添加一个包含零个项目的列表和一个包含一个项目的列表,你最终会得到一个包含一个项目的列表,当然,而不是两个。 (2认同)

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)

    • 代表结果:0.11861872673034668
  • 方法二: c += c_n

    • 代表结果:0.10558319091796875
  • 方法三: c = c + c_n

    • 代表结果:0.25804924964904785
  • 方法四: c = [*c, *c_n]

    • 代表性结果:0.22019600868225098

结论 使用+=.extend()如果您想就地合并。它们的速度要快得多。

  • 我用 python 3.8 对其进行了测试并确认了 Kiran 的结果。请注意,方法 2 使用 INPLACE_ADD 字节码指令,这意味着它就地操作(在同一内存上),因此它比使用 BINARY_ADD 的方法 3 更快 (5认同)
  • @Jonathan 参见 https://docs.python.org/3/library/dis.html (2认同)