How to split a sequence according to a predicate?

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

    If you don't care about efficiency, I think groupby (or any "putting data into n bins" functions) has some nice correspondence,

    by_bins_iter = itertools.groupby(sorted(data, key=pred), key=pred)
    by_bins = dict((k, tuple(v)) for k, v in by_bins_iter)
    

    You can then get to your solution by,

    return by_bins.get(True, ()), by_bins.get(False, ())
    

提交回复
热议问题