I have a list of objects, and I'd like a function that can take that list along with a function operating on the items in that list, and produce a dict with keys from the result of applying that function to the item, and values being a list of items with that key.
Example:
def group_by(iterable: Iterable[A], f: Callable[A, B]) -> Dict[B, List[A]]:
???
lst = [(1,2), (3,4), (1,3)]
result = group_by(lst, lambda i: i[0])
result == {1: [(1,2), (1,3)],
3: [(3,4)]}
itertools.groupby
is close, but I don't want to require that my input be sorted.
Here's an approach with defaultdict
:
from collections import defaultdict
def group_by(iterable, f):
results = defaultdict(list)
for x in iterable:
results[f(x)].append(x)
return results
you are looking for itertools.groupby
from itertools import groupby
groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
# watch out! g is an iterator here, you must iterate it
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
def my_groupby(fn,datum):
d = {}
for data in datum:
d.setdefault(fn(d),[]).append(data)
return d
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.