filter2
Bengt Richter
bokr at oz.net
Sat Jun 15 11:25:10 EDT 2002
On 15 Jun 2002 05:49:33 GMT, quinn at groat.ugcs.caltech.edu (Quinn Dunkan) wrote:
>On Thu, 13 Jun 2002 18:50:23 +0400, Oleg Broytmann <phd at phd.pp.ru> wrote:
>>On Thu, Jun 13, 2002 at 04:39:51PM +0200, Thomas Heller wrote:
>>>
>>> "Oleg Broytmann" <phd at phd.pp.ru> wrote in message
>news:mailman.1023975618.6474.python-list at python.org...
>>> > I want to have new python builtin - filter2. It is exactly like filter,
>>> > but it returns also a list of items that didn't pass the test.
>>>
>>> IIRC, in Smalltalk they were named 'select' (like filter), and 'reject' (like your filter2).
>>> IMO these are much better names then filter and filter2.
>>
>> It is too late to rename builtin filter, so I modelled fiter2 after it.
>
>In haskell they call it "partition" which I think is better since the
>emphasis is that it returns both selected and rejeted.
>
>I wrote mine in python with a plain for loop. I'm not sure C would really get
>you that much efficiency, but it would be easy enough to find out.
>
>Not sure it's worth being in the core (maybe there should be a module for
>list utils or something), but I like partition better than filter2.
I wonder how this version whould do:
>>> def partition(test, alist):
... l2=[]
... return filter(lambda x: test(x) or l2.append(x), alist), l2
...
>>> partition(lambda x: x%3==0, range(16))
([0, 3, 6, 9, 12, 15], [1, 2, 4, 5, 7, 8, 10, 11, 13, 14])
I imagine it's faster than my other one (clipped from other post)
>>> 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