split up a list by condition?

Andrew Dalke dalke at dalkescientific.com
Tue Jun 7 22:41:54 CEST 2005


Reinhold Birkenfeld wrote:
>>> So I think: Have I overlooked a function which splits up a sequence
>>> into two, based on a condition? Such as
>>> 
>>> vees, cons = split(wlist[::-1], lambda c: c in vocals)

> This is clear. I actually wanted to know if there is a function which I
> overlooked which does that, which wouldn't be a maintenance nightmare at
> all.

Not that I know of, but if there is one it should be named
"bifilter", or "difilter" if you prefer Greek roots. :)


def bifilter(test, seq):
  passes = []
  fails = []
  for term in seq:
    if test(term):
      passes.append(term)
    else:
      fails.append(term)
  return passes, fails


>>> bifilter("aeiou".__contains__, "This is a test")
(['i', 'i', 'a', 'e'], ['T', 'h', 's', ' ', 's', ' ', ' ', 't', 's', 't'])
>>> 

Another implementation, though in this case I cheat because I
do the test twice, is

>>> from itertools import ifilter, ifilterfalse, tee
>>> def bifilter(test, seq):
...   seq1, seq2 = tee(seq)
...   return ifilter(test, seq1), ifilterfalse(test, seq2)
... 
>>> bifilter("aeiou".__contains__, "This is another test")
(<itertools.ifilter object at 0x57f050>, <itertools.ifilterfalse object at 0x57f070>)
>>> map(list, _)
[['i', 'i', 'a', 'o', 'e', 'e'], ['T', 'h', 's', ' ', 's', ' ', 'n', 't', 'h', 'r', ' ', 't', 's', 't']]
>>> 


				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list