Simple way to group items into buckets

后端 未结 5 843
耶瑟儿~
耶瑟儿~ 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:33

    This has come up several times before -- (1), (2), (3) -- and there's a partition recipe in the itertools recipes, but to my knowledge there's nothing in the standard library.. although I was surprised a few weeks ago by accumulate, so who knows what's lurking there these days? :^)

    When I need this behaviour, I use

    from collections import defaultdict
    
    def partition(seq, key):
        d = defaultdict(list)
        for x in seq:
            d[key(x)].append(x)
        return d
    

    and get on with my day.

提交回复
热议问题