filter2

Bengt Richter bokr at oz.net
Fri Jun 14 19:57:36 EDT 2002


On Fri, 14 Jun 2002 09:33:10 GMT, Michael Hudson <mwh at python.net> wrote:

>huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) writes:
>
>> It's not that gross, but it only gives 14% speedup, though.
>
>Oh yeah.  What you've done is kind of obvious...
>
>> 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)?
>
>Look at BINARY_SUBSCR in ceval.c... list[int] is special-cased.
>
Try this one:

 >>> def filter3(test, alist): # not to use keyword
 ...     l2=[]
 ...     return [x for x in alist if test(x) or l2.append(x)], l2
 ...
 >>> print filter3(lambda x: x%3==0,range(16))
 ([0, 3, 6, 9, 12, 15], [1, 2, 4, 5, 7, 8, 10, 11, 13, 14])

Regards,
Bengt Richter



More information about the Python-list mailing list