from timeit import Timer def test(): li=[] for i in range(10000): li.append(i) def test2(): li=[i for i in range(10000)] t=Timer("test()","from __main__ import test") print("for循环生成list:",t.timeit(1000)) t2=Timer("test2()","from __main__ import test2") print("列表生成式生成ist:",t2.timeit(1000))
结果:
for循环生成list: 1.1254361433275843 列表生成式生成ist: 0.40410030265129304