I was doing a bit of Python at work and need to filter an array, all the values at the odd indexes into one array, all the one at the even indices into the other array. What I came up with is this:
class everyother:
"""Helper class for picking out
every other item when filtering
an array."""
def __init__(self, start):
self.start = start
def next(self, a):
self.start = not self.start
return self.start
Now I can use this to filter
arrays.
>>> v = map(hex, range(20)) >>> v ['0x0', '0x1', '0x2', ..., '0x13'] >>> evens = filter(everyother(0).next, v) >>> evens ['0x1', '0x3', '0x5', '0x7', '0x9', '0xb', '0xd', '0xf', '0x11', '0x13']
Cool, but I can't help wonder if there's a better way to do this in Python.
Updated: I forgot about list comprehensions. Sam offered this one-liner:
>>> odds = [v[i] for i in range(1, len(v), 2)]
>>> evens = [v[i] for i in range(0, len(v), 2)]
Woot!
Not necessarily “better“, but definitely “different”
from future import generators
def odds(list):
for i in range(1, len(v), 2):
yield i
m = odds(v)
for i in m:
print i
Posted by Gordon Weakliem on 2003-06-18
Not necessarily “better“, but definitely “different”
from future import generators
def odds(list):
for i in range(1, len(v), 2):
yield i
m = odds(v)
for i in m:
print i
Posted by Gordon Weakliem on 2003-06-18
In Python 2.3 (currently beta):
>>> evens = v[::2]
>>> odds = v[1::2]
Search for “extended slices” for more info.
Posted by Arien on 2003-06-19
Sweeet!
Found the docs:
http://www.python.org/dev/doc/devel/whatsnew/section-slices.html
You can even to v[::-1] to reverse the list.
Posted by Joe on 2003-06-19
[v[i] for i in range(1,len(v),2)]
Posted by Sam Ruby on 2003-06-18