Quantcast
Channel: How can I partition (split up, divide) a list based on a condition? - Stack Overflow
Viewing all articles
Browse latest Browse all 41

Answer by Jim Witschey for How can I partition (split up, divide) a list based on a condition?

$
0
0

I'd take a 2-pass approach, separating evaluation of the predicate from filtering the list:

def partition(pred, iterable):    xs = list(zip(map(pred, iterable), iterable))    return [x[1] for x in xs if x[0]], [x[1] for x in xs if not x[0]]

What's nice about this, performance-wise (in addition to evaluating pred only once on each member of iterable), is that it moves a lot of logic out of the interpreter and into highly-optimized iteration and mapping code. This can speed up iteration over long iterables, as described in this answer.

Expressivity-wise, it takes advantage of expressive idioms like comprehensions and mapping.


Viewing all articles
Browse latest Browse all 41

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>