3 ms·
Nice lambda. You've defended yourself admirably. Did you know there's an `operator.itemgetter` function that does that? So that's: >>> sorted(((x, -(x**2))
by aaronchall 11y ago
Nice lambda. You've defended yourself admirably. Did you know there's an `operator.itemgetter` function that does that?
So that's:
>>> sorted(((x, -(x**2)) for x in xrange(10) if 0 == x % 2), key=operator.itemgetter(1))
[(8, -64), (6, -36), (4, -16), (2, -4), (0, 0)]
Do note that good code and code golf are two different things! :D
- merlincorey 11y ago> Nice lambda. You've defended yourself admirably. Thanks! > Did you know there's an `operator.itemgetter` function that does that? Yes, I'm quite aware! Are you aware the "useless" functional solution with lambda is two characters shorter? >>> len('lambda item: item[1]') 20 >>> len('operator.itemgetter(1)') 22 Cause you're apparently not aware that I was demonstrating a use-case for lambdas as one-off functions that are passed to other functions (which is an abstract concept from the particular function used), and you didn't demonstrate how list comprehensions or generators make them not-needed. Of course, that's because it was a leading question and the answer is that the concepts are orthogonal so it cannot be demonstrated.
- ectoplasm 11y agoI bet you two would be good friends IRL.
- aaronchall 11y agoI'm sure we would. I'll buy the first drink. :D