Simple way to group items into buckets

后端 未结 5 836
耶瑟儿~
耶瑟儿~ 2020-12-29 08:48

I often want to bucket an unordered collection in python. itertools.groubpy does the right sort of thing but almost always requires massaging to sort the items first and cat

5条回答
  •  臣服心动
    2020-12-29 09:40

    Here's a variant of partition() from above when the predicate is boolean, avoiding the cost of a dict/defaultdict:

    def boolpartition(seq, pred):
        passing, failing = [], []
        for item in seq:
            (passing if pred(item) else failing).append(item)
        return passing, failing
    

    Example usage:

    >>> even, odd = boolpartition([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
    >>> even
    [2, 4]
    >>> odd
    [1, 3, 5]
    

提交回复
热议问题