filter2
Jeff Epler
jepler at unpythonic.net
Thu Jun 13 12:06:02 EDT 2002
On Thu, Jun 13, 2002 at 03:00:28PM +0000, Michael Hudson wrote:
> Write it in Python. Particularly if test is expensive the loop
> overhead will disappear into the noise.
>
> (with-seriousness-level :low
> If you insist on C loops, there's always:
>
> lt = map(lambda x:(test(x), x), alist)
> l1 = filter(lambda (x,y):x, lt)
> l2 = filter(lambda (x,y):not x, lt)
>
> But I doubt you need me to tell you why this solution sucks.)
If you're benchmarking, try a solution like this in the mix. It only
has one map/filter call, not map+2*filter. (uses nested scopes and the
new bool() builtin, but this can be avoided if necessary)
def filter2(test, list):
l1 = []
l2 = []
funcs = [l2.append, l1.append]
map(lambda x: funcs[bool(test(x))](x), list)
return l1, l2
>>> print filter2(lambda x: x%3==0, range(16))
([0, 3, 6, 9, 12, 15], [1, 2, 4, 5, 7, 8, 10, 11, 13, 14])
Jeff
More information about the Python-list
mailing list