Python: split a list based on a condition?

前端 未结 30 2559
误落风尘
误落风尘 2020-11-22 06:56

What\'s the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 07:25

    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.

提交回复
热议问题