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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With