测试哪种循环速度最快

测试哪种循环速度最快


import time

def test1():
    """普通for循环的列表相加法"""
    l = []
    for i in range(20000):
        l = l + [i]

def test2():
    """普通for循环的append方法"""
    l = []
    for i in range(20000):
        l.append(i)

def test3():
    """列表推导式"""
    l = [i for i in range(20000)]
    
def test4():
    """用list和range命令相结合"""
    l = list(range(20000))

def test5():
    """用while循环和insert"""
    c = 0
    l = []
    while c<20000:
        l.insert(0,c) # 由于每次都要整体往右移所有数据,所以最慢! O(n)!
        c += 1
        
start = time.time()
print(test1(),time.time()-start)
print()

start = time.time()
print(test2(),time.time()-start)
print()

start = time.time()
print(test3(),time.time()-start)
print()

start = time.time()
print(test4(),time.time()-start)
print()


start = time.time()
print(test5(),time.time()-start)
print()


李兴球

李兴球的博客是Python创意编程原创博客