filter2
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Thu Jun 13 21:38:17 EDT 2002
Michael Hudson <mwh at python.net> wrote:
>Jeff Epler <jepler at unpythonic.net> writes:
>>
>> 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])
>
>Hey, that's pretty neat! Still three function calls per element,
>though. Well, four including bool, but that could be gotten rid of by
>gross hacks (e.g. not not test(x)).
It's not that gross, but it only gives 14% speedup, though.
def filter2a(test, list):
l1 = []
l2 = []
funcs = [l1.append, l2.append]
map(lambda x: funcs[not test(x)](x), list)
return l1, l2
BTW, what's the reason that using a list for funcs is faster than using a
tuple (as observed under Python 2.2.1 on Linux)?
Huaiyu
More information about the Python-list
mailing list