python列表处理效率对比测试

发布时间:2019-08-06 13:56:23编辑:auto阅读(1709)

    Python列表添加元素效率测试

    #!/usr/bin/env
    import datetime
    class adair:
        def test1(n):
            lst=[]
            for i in range(n*10000):
                lst = lst + [i]
            return lst
    
        def test2(n):
            for i in range(n*10000):
                lst = lst.append(i)
            return lst
    
        def test3(n):
            return [i for i in range(n*10000)]
    
        def test4(n):
            return list(range(n*10000)
    
    if __name__ == '__main__':    
        f=adair()
        start = datetime.datetime.now()
        f.test1(2)
        end = datetime.datetime.now()
        print(end-start)
    
        start = datetime.datetime.now()
        f.test2(2)
        end=datetime.datetime.now()
        print(end-start)
    
        start=datetime.datetime.now()
        f.test3(2)
        end=datetime.datetime.now()
        print(end-start)
    
        start=datetime.datetime.now()
        f.test4(2)
        end=datetime.datetime.now()
        print(end-start)

    测试结果如下:
    python列表处理效率对比测试

关键字