Re:Functools – The Power of Higher-Order Functions in Python
by quietbritishjim on Friday July 09, 2021 @06:45AM
(#27782338)
Hmm, you're right... that one is actually quite hard to do in a Python-ish way. There is a one liner, just for the record, but it's absolutely horrific code because it redundantly re-evaluates the same conditions over and over:
g = {fn(x): [y for y in foo if f(y)==f(x)] for x in foo}
As you said, you'd have to use a for loop. I think sometimes people are unnecessarily afraid of for loops in Python (not everything has to fit on one line!) but this is a case it's a pity to take up so many lines. Or, back to square one, probably this is a case it's best just to use itertools groupby (after a sort) after all.
For example if
“def fn(i): return i//2”
You probably want to get an output like {0: [0,1]} but you’ll only get a scalar for the value (1) and it will be the last one evaluated.
It would be nice if there was a way to do this on one line but you’ll have to do
ret=collections.defaultdict(list) For i In foo: ret[fn(i)].append(i) Return ret
I suppose it isn’t that bad as it will be in the groupBy method.
Or you could add it to a method on a list. I think that’s easier to do with Rust.