How to split a sequence according to a predicate?

后端 未结 6 1251
既然无缘
既然无缘 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:48

    I know you said you didn't want to write your own function, but I can't imagine why. Your solutions involve writing your own code, you just aren't modularizing them into functions.

    This does exactly what you want, is understandable, and only evaluates the predicate once per element:

    def splitter(data, pred):
        yes, no = [], []
        for d in data:
            if pred(d):
                yes.append(d)
            else:
                no.append(d)
        return [yes, no]
    

    If you want it to be more compact (for some reason):

    def splitter(data, pred):
        yes, no = [], []
        for d in data:
            (yes if pred(d) else no).append(d)
        return [yes, no]
    

提交回复
热议问题