python:loop vs comprehension

This question already has an answer here:

  • Are list-comprehensions and functional functions faster than “for loops”? 5 answers

  • You can use the timeit library, or just use time.time() to time it yourself:

    >>> from time import time
    >>> def first():
    ...     ftime = time()
    ...     _foo = [x ** 2 for x in range(1, 101)]
    ...     print "First", time()-ftime
    ... 
    >>> def second():
    ...     ftime = time()
    ...     _foo = []
    ...     for x in range(1, 101):
    ...             _b=[x**2]
    ...             _foo+=_b
    ...     print "Second", time()-ftime
    ... 
    >>> first()
    First 5.60283660889e-05
    >>> second()
    Second 8.79764556885e-05
    >>> first()
    First 4.88758087158e-05
    >>> second()
    Second 8.39233398438e-05
    >>> first()
    First 2.8133392334e-05
    >>> second()
    Second 7.29560852051e-05
    >>> 
    

    Evidently, the list comprehension runs faster, by a factor of around 2 to 3.

    链接地址: http://www.djcxy.com/p/69946.html

    上一篇: 为什么列表理解如此之快?

    下一篇: python:循环与理解