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
>>> 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)]