Python 连接与列表上的追加速度 [英] Python concatenation vs append speed on lists

查看:28
本文介绍了Python 连接与列表上的追加速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从interactivepython.org 获取这个片段:

Taking this snippet from interactivepython.org:

def test1():  # concat
    l = []
    for i in range(1000):
        l = l + [i]

def test2():  # append
    l = []
    for i in range(1000):
        l.append(i)

<小时>

concat  6.54352807999 milliseconds
append  0.306292057037 milliseconds

底部块是运行时间.

它说连接是 O(k),其中 k 是被连接的列表的长度".我不确定这是否意味着您要添加到(原始)的列表,或者您要添加的列表.但是在这两个循环中,您似乎每次迭代只执行 1 步.那么为什么 append 的速度要快得多?

It says concatenation is O(k), where k is the "length of the list being concatenated". I'm not sure if this means the list you are adding to (original), or the list you are going to be adding. But in both these loops it seems like you are just performing 1 step per iteration. So why is append so much faster?

推荐答案

如果将 test1 更改为:

If you change test1 to:

def test1():  # concat
    l = []
    for i in range(1000):
        l += [i] 

时间会更近,而您实际上正在做 append 不会每次都创建一个新列表的操作.

the times will be much closer and you are actually doing what append is doing not creating a new list each time.

In [26]: %timeit test1()
10000 loops, best of 3: 169 µs per loop

In [27]: %timeit test2()
10000 loops, best of 3: 115 µs per loop

如果你把 print id 放在你的代码中,你会在 test1 中看到你每次都在创建一个新对象,但在 test2 中它是总是同一个列表:

If you put print id in your code you will see in test1 you are creating a new object each time but in test2 it is always the same list:

In [41]: test1()
139758194625352
139758206001808
139758205966960
139758194625352
139758206001808
139758205966960
139758194625352
139758206001808
139758205966960
139758194625352
Out[41]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [42]: test2()
139758206002600
139758206002600
139758206002600
139758206002600
139758206002600
139758206002600
139758206002600
139758206002600
139758206002600
139758206002600
Out[42]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

这篇关于Python 连接与列表上的追加速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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