In my evolved answer to this question, I came up with a way to do a single line (well, single expression) reduce
to create the results of groupby
as defined by many other languages (Kotlin, ObjC, Swift, Smalltalk, at least).
My initial attempt looked like:
def keyFunc(value):
return derivative_of_value
grouped = reduce(
lambda accum, each: accum[keyFunc(each)].append(each),
allValues,
defaultdict(list))
As stated in my Aside/Tangent there, the problem is the lambda. A lambda is limited to a single expression. And for it to work in reduce, it must return a modified version of the accumulated argument.
So I came up with the following hack, using a tuple to move the dict reference from reduction to reduction, but also force the (ignored) side effect of updating the same dict:
from functools import reduce
grouped = reduce(
lambda accum, each: (accum[0], accum[0][keyFunc(each)].append(each)),
allValues,
(defaultdict(list), None))[0]
The Question is... is there a better way? Given the constraint that I want to try and still use a single expression reduce without a bunch of helper functions.
(I recognize that sometimes the code is telling you something, but I'm interested in this case for the academic side of things)