By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,285 Members | 1,687 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,285 IT Pros & Developers. It's quick & easy.

list partition

P: n/a
Is there a function that takes a list and predicate, and returns two
lists -- one for which the predicate is true and one for which it is false?

I know I can call filter(p, list) and filter( not p, list) or something like
that, but I assume it would be more efficient to do it in one pass.

Actually I probably can't call "not p", I would have to wrap p in a function
notP or something. Or is there a shortcut for lambda(x) : not p(x)? I
guess it isn't that long : )

MB
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Moosebumps wrote:
Is there a function that takes a list and predicate, and returns two
lists -- one for which the predicate is true and one for which it is
false?


I take a slightly different approach, which is not limited to boolean
predicates:
def predicate(v): return v & 1 .... d = {}
for i in range(10): .... d.setdefault(predicate(i), []).append(i)
.... d[True] [1, 3, 5, 7, 9] d[False] [0, 2, 4, 6, 8]


Peter
Jul 18 '05 #2

P: n/a
At some point, "Moosebumps" <Mo********@Moosebumps.Moosebumps> wrote:
Is there a function that takes a list and predicate, and returns two
lists -- one for which the predicate is true and one for which it is false?

I know I can call filter(p, list) and filter( not p, list) or something like
that, but I assume it would be more efficient to do it in one pass.
Not too hard to write your own:

def filtersplit(p, iterable):
ptrue = []
pfalse = []
for x in iterable:
if p(x):
ptrue.append(x)
else:
pfalse.append(x)
return ptrue, pfalse
Actually I probably can't call "not p", I would have to wrap p in a function
notP or something. Or is there a shortcut for lambda(x) : not p(x)? I
guess it isn't that long : )


itertools.ifilterfalse negates the condition for you.

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.