Python几种创建list的方法的效率对比

本文转载自: https://www.cnblogs.com/pythonchan/p/6213675.html 作者:PythonChan 转载请注明该声明。

我们用 生成一个0到((1万倍n)-1)的list做例子

<a href='https://www.itdaan.com/keywords/Python几种创建list的方法的效率对比.html' target='_self'>Python</a>几种创建list的方法的效率对比

首先这种方式复杂度为平方级

'''

def test1(n):

lst = []

for i in range(n*10000):

lst = lst + [i]

return lst

'''

Python几种创建list的方法的效率对比

如n=5,平均运行花费3秒2;

如果n=10的话,平均运行花费飙到14秒9;

是因为复制一个长度为n的list,本身的复杂度就是线性级的了。

###############################################################

接下来这几种,时间复杂度都是线性级的

Python几种创建list的方法的效率对比

‘’‘

def test2(n):

lst = []

for i in range(n*10000):

lst.append(i)

return lst

def test3(n):

return [i for i in range(n*10000)]

def test4(n):

return list(range(n*10000))

’‘’

Python几种创建list的方法的效率对比我们来对比一下,到底哪个快

Python几种创建list的方法的效率对比

测试后可以发现,直接用系统list方法是最快的,然后是列表推导,用list类的append方法排后。

头条号 PythonChan

发布了0 篇原创文章 · 获赞 72 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/w36680130/article/details/103867850