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 catch the iterators before they’re consumed.
Is there any quick way to get this behavior, either through a standard python module or a simple python idiom?
>>> bucket('thequickbrownfoxjumpsoverthelazydog', lambda x: x in 'aeiou')
{False: ['t', 'h', 'q', 'c', 'k', 'b', 'r', 'w', 'n', 'f', 'x', 'j', 'm', 'p',
's', 'v', 'r', 't', 'h', 'l', 'z', 'y', 'd', 'g'],
True: ['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'a', 'o']}
>>> bucket(xrange(21), lambda x: x % 10)
{0: [0, 10, 20],
1: [1, 11],
2: [2, 12],
3: [3, 13],
4: [4, 14],
5: [5, 15],
6: [6, 16],
7: [7, 17],
8: [8, 18],
9: [9, 19]}
This has come up several times before — (1), (2), (3) — and there’s a partition recipe in the
itertoolsrecipes, but to my knowledge there’s nothing in the standard library.. although I was surprised a few weeks ago byaccumulate, so who knows what’s lurking there these days? :^)When I need this behaviour, I use
and get on with my day.