filter2

Michael Hudson mwh at python.net
Thu Jun 13 11:00:28 EDT 2002


Oleg Broytmann <phd at phd.pp.ru> writes:

> Hello!
> 
>    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.
> 
>    Of course I can do it with just "for" loop:
> 
> l1 = []
> l2 = []
> for item in alist:
>    if test(item):
>       l1.append(item)
>    else:
>       l2.append(item)
> 
> but this way I am missing filter's loop written in C.

Not much, I suspect.

>    Running filter two times (with test and inverted test) is not an option,
> as test could be a costly function.
> 
>    Opinions?

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

Cheers,
M.

-- 
  I'm not sure that the ability to create routing diagrams 
  similar to pretzels with mad cow disease is actually a 
  marketable skill.                                     -- Steve Levin
               -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html



More information about the Python-list mailing list