pairs from a list

Arnaud Delobelle arnodel at googlemail.com
Tue Jan 22 11:09:01 EST 2008


On Jan 22, 1:19 pm, Alan Isaac <ais... at american.edu> wrote:
> I suppose my question should have been,
> is there an obviously faster way?
> Anyway, of the four ways below, the
> first is substantially fastest.  Is
> there an obvious reason why?

Can you post your results?

I get different ones (pairs1 and pairs2 rewritten slightly to avoid
unnecessary indirection).

====== pairs.py ===========
from itertools import *

def pairs1(x):
    return izip(islice(x,0,None,2),islice(x,1,None,2))

def pairs2(x):
    xiter = iter(x)
    while True:
        yield xiter.next(), xiter.next()

def pairs3(x):
    for i in range( len(x)//2 ):
        yield x[2*i], x[2*i+1],

def pairs4(x):
    xiter = iter(x)
    return izip(xiter,xiter)

def compare():
    import timeit
    for i in '1234':
        t = timeit.Timer('list(pairs.pairs%s(l))' % i,
                         'import pairs; l=range(1000)')
        print 'pairs%s: %s' % (i, t.timeit(10000))

if __name__ == '__main__':
    compare()
=====================

marigold:python arno$ python pairs.py
pairs1: 0.789824962616
pairs2: 4.08462786674
pairs3: 2.90438890457
pairs4: 0.536775827408

pairs4 wins.

--
Arnaud




More information about the Python-list mailing list