Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List splitting by predicate

Tags:

python

Is there a more concise way to split a list into two lists by a predicate?

errors, okays = [], []
for r in results:
    if success_condition(r):
        okays.append(r)
    else:
        errors.append(r)

I understand that this can be turned into an ugly one-liner using reduce; this is not what I'm looking for.

Update: calculating success_condition only once per element is desirable.

like image 819
9000 Avatar asked Aug 15 '12 18:08

9000


1 Answers

Maybe

for r in results:
    (okays if success_condition(r) else errors).append(r)

But that doesn't look/feel very Pythonic.


Not directly relevant, but if one is looking for efficiency, caching the method look-ups would be better:

okays_append = okays.append
errors_append = errors.append

for r in results:
    (okays_append if success_condition(r) else errors_append)(r)

Which is even less Pythonic.

like image 121
huon Avatar answered Sep 21 '22 16:09

huon