python - How to get the groups generated by "groupby()" as lists? -
i testing itertools.groupby()
, try groups lists can't figure out how make work.
using examples here, in how use python's itertools.groupby()?
from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
i tried (python 3.5):
g = groupby(things, lambda x: x[0]) ll = list(g) list(tuple(ll[0])[1])
i thought should first group ("animal") list ['bear', 'duck']
. empty list on repl.
what doing wrong?
how should extract 3 groups lists?
if want groups, without keys, need realize group generators go, per docs:
because source shared, when groupby() object advanced, previous group no longer visible. so, if data needed later, should stored list.
this means when try list
-ify groupby
generator first using ll = list(g)
, before converting individual group generators, last group generator invalid/empty.
(note list
1 option; tuple
or other container works too).
so properly, you'd make sure list
ify each group generator before moving on next:
from operator import itemgetter # nicer ad-hoc lambdas # make key, group generator gen = groupby(things, key=itemgetter(0)) # strip keys; care group generators # in python 2, you'd use future_builtins.map, because non-generator map break groups = map(itemgetter(1), gen) # convert them list 1 one before next group pulled groups = map(list, groups) # , listify result (to run out generator , # results, assuming need them list groups = list(groups)
as one-liner:
groups = list(map(list, map(itemgetter(1), groupby(things, key=itemgetter(0)))))
or because many map
s gets rather ugly/non-pythonic, , list comprehensions let nifty stuff unpacking named values, can simplify to:
groups = [list(g) k, g in groupby(things, key=itemgetter(0))]
Comments
Post a Comment