LISTS: Extract every other element

Randall Hopper aa8vb at yahoo.com
Mon Dec 20 12:17:16 EST 1999


   eric jones:
   Mike Fletcher:
      |>>> from Numeric import *
      |>>> a = array(range(10))
      |>>> a[::2]

Pretty fast.

   Christian Tismer:
      |def slice100(d):

Most impressive.  Not as readable, but amazing performance without having
to resort to a C extension.

   Charles Boncelet:
      |import NewBuiltins # (mxTools)
      |lst2=extract(lst,trange(0,len(lst),2))

Fastest yet.

Thanks for the tips!  This has been fun and educational.  Here are the
latest results, operating on the same test list:

   [ 0, 10, 20, 30, 40, 50, 60, 70 ] * 100000


                   Using range()                    Using xrange()
               -----------------------------------------------------------
APPROACH #1  |  100.00%  (2.09307 sec)     |     100.00%  (1.99558 sec)  *
APPROACH #1b |   95.04%  (1.98935 sec)     |      98.17%  (1.95897 sec)  *
APPROACH #2  |  689.31%  (14.4278 sec)     |     729.60%  (14.5598 sec)  *
APPROACH #2b |  593.99%  (12.4327 sec)     |     619.72%  (12.3671 sec)  *
APPROACH #3  |  121.90%  (2.55138 sec)     |     120.36%  (2.40184 sec)  *
APPROACH #4  |  322.12%  (6.74217 sec)     |     338.34%  (6.75179 sec) 
APPROACH #4b |  702.62%  (14.7063 sec)     |     743.19%  (14.831 sec)  
APPROACH #5  |  108.82%  (2.27761 sec)     |     108.68%  (2.1688 sec)   *
APPROACH #6  |   67.31%  (1.4088 sec)      |      70.02%  (1.39727 sec) 
APPROACH #7  |   67.58%  (1.4146 sec)      |      70.17%  (1.40032 sec) 
APPROACH #8  |   33.29%  (0.696691 sec)    |      34.40%  (0.686397 sec) *
APPROACH #9  |   31.34%  (0.656048 sec)    |      34.14%  (0.681241 sec)

                                * = uses range/xrange

-----------------------------------------------------------------------------
APPROACH KEY:

APPROACH #1  - Original "for loop" implementation
APPROACH #1b - #1 but use multiply rather than divide
APPROACH #2  - filter( lambda a: a != None,
                       map( even_select, lst, range(len(lst)) )
APPROACH #2b - map( second, filter( odd, map( None, range(len(lst)), lst ) ) )
APPROACH #3  - map( lambda x: lst[x], range(0, len(lst), 2) )
APPROACH #4  - filter( on_off, lst ) , where on_off() funct alternates 1/0
APPROACH #4b - filter( onoff(), lst ), where onoff() class instance alt's 1/0
APPROACH #5  - a = Numeric.array( lst, 'O' )
               lst2 = list( Numeric.take( a, range(0,len(a),2) ) )
APPROACH #6  - data = Numeric.array( lst, Numeric.Int32 )
               data.shape = ( -1, step )
               lst2 = list( data[:,0] )
APPROACH #7  - lst2 = list( Numeric.array( lst, Numeric.Int32 )[::2] )
APPROACH #8  - Christian's 100 element walker
APPROACH #9  - lst2 = mxTools.extract( lst, mxTools.trange( 0, len(lst), 2 ) )

-----------------------------------------------------------------------------

--
Randall Hopper
aa8vb at yahoo.com




More information about the Python-list mailing list