LISTS: Extract every other element
Charles G Waldman
cgw at fnal.gov
Thu Dec 16 14:38:58 EST 1999
Skip Montanaro writes:
>
> Randall> I want to take a large list:
> Randall> [ 1,2,3,4,5,6,7,... ]
>
> Randall> and build a list with every other element:
> Randall> [ 1,3,5,7,... ]
>
> Randall> Is there a faster way than looping over indices?:
>
> I'm pretty sure you can do this with NumPy. I'm not a NumPy user though, so
> I'll have to defer to the rocket scientists... ;-)
>
(Disclaimer: I may work at a government lab, but I'm not a rocket
scientist)
You could do this:
>>> from Numeric import *
>>> a = array(mylist, 'O')
>>> b = take(a,range(0,len(a),2)
For the case where "mylist" is a list of numbers, this works fine:
>>> mylist = [3,1,4,1,5,9,2,6,5,3,6]
>>> a = array(mylist, 'O')
>>> b = take(a,range(0,len(a),2)
>>> b
array([3 , 4 , 5 , 2 , 5 , 6 ],'O')
It *should* work for general lists, using Numeric arrays of type 'O'
(Python Object).
However, in the course of writing and testing this I found a bug in
Numeric, where it mis-handles initialization of arrays of type 'O'
(Python Object).
>>> from Numeric import array
>>> l = ['abc','def','ghi']
>>> array(l,'O')
array([[abc , abc , abc ],
[def , def , def ],
[ghi , ghi , ghi ]],'O')
Oops! That should have been
array([abc, def, ghi], 'O')
So, in fact, you *could* use Numeric to do this, if it weren't
broken. Sigh. I'm taking this thread over to the Matrix-SIG.
More information about the Python-list
mailing list