Python几种列表生成方式的性能比较


from timeit import Timer
import functools


def test_time(number):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            t = Timer(func, "from __main__ import " + func.__name__)
            print(t.timeit(number))
        return wrapper
    return decorator


@test_time(10000)
def test1():
    l = []
    for i in range(1000):
        l += [i]


@test_time(10000)
def test2():
    l = []
    for i in range(1000):
        l.append(i)


@test_time(10000)
def test3():
    l = [i for i in range(1000)]


@test_time(10000)
def test4():
    l = list(range(1000))


test1()
test2()
test3()
test4()

输出结果为:

0.9504628766087785
0.838232950894074
0.3771211559417289
0.15597873161463482

很明显:

range最快

其次是列表推导式

再次是append

最后是列表连接

上一篇:01:查找特定的值


下一篇:05:最大值和最小值的差