
On Tue, Jul 3, 2018, 6:32 PM Steven D'Aprano steve@pearwood.info wrote:
On Tue, Jul 03, 2018 at 10:33:55AM -0700, Chris Barker wrote:
On Tue, Jul 3, 2018 at 8:33 AM, Steven D'Aprano steve@pearwood.info
wrote:
but why are we using key values by hand when grouping ought to do it
for
us, as Michael Selik's version does?
grouping(words, key=len)
because supplying a key function is sometimes cleaner, and sometimes
uglier
than building up a comprehension -- which I think comes down to:
taste (style?)
whether the key function is as simple as the expression
whether you ned to transform the value in any way.
Of course you can prepare the sequence any way you like, but these are not equivalent:
grouping(words, keyfunc=len) grouping((len(word), word) for word in words)
The first groups words by their length; the second groups pairs of (length, word) tuples by equality.
py> grouping("a bb ccc d ee fff".split(), keyfunc=len) {1: ['a', 'd'], 2: ['bb', 'ee'], 3: ['ccc', 'fff']}
py> grouping((len(w), w) for w in "a bb ccc d ee fff".split()) {(3, 'ccc'): [(3, 'ccc')], (1, 'd'): [(1, 'd')], (2, 'ee'): [(2, 'ee')], (3, 'fff'): [(3, 'fff')], (1, 'a'): [(1, 'a')], (2, 'bb'): [(2, 'bb')]}
This handles the case that someone is passing in n-tuple rows and wants to keep the rows unchanged.