[issue43899] separate builtin function

Raymond Hettinger report at bugs.python.org
Tue Apr 20 18:57:43 EDT 2021


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

FWIW, here's a recipe from the itertools docs:

    def partition(pred, iterable):
        "Use a predicate to partition entries into false entries and true entries"
        # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
        t1, t2 = tee(iterable)
        return filterfalse(pred, t1), filter(pred, t2)


Also, here's a more general solution that can handle multiple categories:

    >>> from collections import defaultdict
    >>> def categorize(func, iterable):
            d = defaultdict(list)
            for x in iterable:
                d[func(x)].append(x)
            return dict(d)

    >>> categorize(is_positive, [-3, -2, -1, 0, 1, 2, 3])
    {False: [-3, -2, -1, 0], True: [1, 2, 3]}
    >>> categorize(lambda x: x%3, [-3, -2, -1, 0, 1, 2, 3])
    {0: [-3, 0, 3], 1: [-2, 1], 2: [-1, 2]}


At one point, Peter Norvig suggested adding a groupby classmethod to dictionaries.  I would support that idea.   Something like:

    dict.groupby(attrgetter('country'), conferences)

----------
nosy: +rhettinger

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43899>
_______________________________________


More information about the Python-bugs-list mailing list