python list拼接四种方式速度对比

1.for循环+

def fun1():
    l = []
    for i in range(1000):
        l = l + [i]

2.for循环append

def fun2():
    l = []
    for i in range(1000):
        l.append(i)

3.生成器

def fun3():
    l = [i for i in range(1000)]

4.list加range

def fun4():
    l = list(range(1000))

速度对比选择Python库timeit

t1 = Timer("fun1()", "from __main__ import fun1")
print("concat:",t1.timeit(number=1000), "milliseconds")
t2 = Timer("fun2()", "from __main__ import fun2")
print("concat:",t2.timeit(number=1000), "milliseconds")
t3 = Timer("fun3()", "from __main__ import fun3")
print("concat:",t3.timeit(number=1000), "milliseconds")
t4 = Timer("fun4()", "from __main__ import fun4")
print("concat:",t4.timeit(number=1000), "milliseconds")

运行结果:

concat: 0.767764812 milliseconds
concat: 0.057362731 milliseconds
concat: 0.027215053000000045 milliseconds
concat: 0.014774799999999977 milliseconds

 

你可能感兴趣的:(python)