循环连接列表 append添加 列表推导式 range函数转换
代码呈现:
from timeit import Timer def one(): """循环连接列表""" l = [] for i in range(1000): l = l + [i] def two(): """append添加""" l = [] for i in range(1000): l.append(i) def three(): """列表推导式""" l = [i for i in range(1000)] def four(): """range函数转换""" l = list(range(1000)) T1 = Timer("one()", "from __main__ import one") print("one: %f sec\n" % T1.timeit(number=1000)) T2 = Timer("two()", "from __main__ import two") print("two: %f sec\n" % T2.timeit(number=1000)) T3 = Timer("three()", "from __main__ import three") print("three: %f sec\n" % T3.timeit(number=1000)) T4 = Timer("four()", "from __main__ import four") print("four: %f sec\n" % T4.timeit(number=1000))
结果:
one: 1.095957 sec two: 0.057843 sec three: 0.027013 sec four: 0.011470 sec