How to split a sequence according to a predicate?

后端 未结 6 1249
既然无缘
既然无缘 2020-12-20 10:52

I very often run into the need to split a sequence into the two subsequences of elements that satisfy and don\'t satisfy a given predicate (preserving the original relative

6条回答
  •  一向
    一向 (楼主)
    2020-12-20 11:35

    Partitioning is one of those itertools recipes that does just that. It uses tee() to make sure it's iterating the collection in one pass despite the multiple iterators, the builtin filter() function to grab items that satisfies the predicate as well as filterfalse() to get the opposite effect of the filter. This is as close as you're going to get at a standard/builtin method.

    def partition(pred, iterable):
        'Use a predicate to partition entries into false entries and true entries'
        # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
        t1, t2 = tee(iterable)
        return filterfalse(pred, t1), filter(pred, t2)
    

提交回复
热议问题