Message391484
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) |
|
Date |
User |
Action |
Args |
2021-04-20 22:57:43 | rhettinger | set | recipients:
+ rhettinger, alvarezdqal |
2021-04-20 22:57:43 | rhettinger | set | messageid: <1618959463.73.0.107808336836.issue43899@roundup.psfhosted.org> |
2021-04-20 22:57:43 | rhettinger | link | issue43899 messages |
2021-04-20 22:57:42 | rhettinger | create | |
|