关于for循环的速度优化

用列表推导式代替for循环创建列表

@timmer
def test1():
    a = []
    for i in range(100000):
        a.append(i)
    # print(a)

@timmer
def test2():
    a = [i for i in range(100000)]
    # print(a)
函数:test1() 开始运行:
函数: test1() 运行了 0.006981849670410156秒

函数:test2() 开始运行:
函数: test2() 运行了 0.003988742828369141秒

速度提高了很多

 

posted @ 2020-07-17 11:31  秋夜花开  阅读(1482)  评论(0编辑  收藏  举报