pivot() equivalent

gundlach gundlach at gmail.com
Fri Mar 12 00:16:36 CET 2010


I *know* this already exists, but I can't remember where:

def pivot(func, seq):
  # I know, a good implementation shouldn't call func() twice per item
  return ( (x for x in seq if func(x)), (x for x in seq if not
func(x)) )

I feel like I read a thread in which this was argued to death, and I
can't find that either.

The scenario: I have a sequence of lines from a file.  I want to split
it into those lines that contain a substring, and those that don't.  I
want it to be more efficient and prettier than

with = [x for x in lines if substring in x]
without = [x for x in lines if substring not in x]

Does this exist?

TIA,
Michael



More information about the Python-list mailing list