+ 11
Python trouble with groupby
While writing my code for 'anadrome' challenge, I wanted to use groupby from itertools module. My goal is to sort strings in two groups whether they have an even/odd number of characters. The result surprised me: there are multiple groups for each key... See my code to get what I mean. My question : what happens + how can I get it right? https://code.sololearn.com/cd75P2c5FgKh/?ref=app
12 Respuestas
+ 10
I think this fixes it but collections.Counter is better for this in my opinion collections.Counter('tooth') #Counter({'t': 2, 'o': 2, 'h': 1})
letters.sort(key=lambda x:len(x)%2)
+ 9
michal
I think you're right.
(it was not obvious first, I think you wrote nn instead of ll).
Strange behaviour to group only neighbour's...
Thank you 😊
+ 9
Kishalaya Saha
Oups,... Great ! That was in the doc. I had an eye on the doc, should have used both 😅
Thank you !
+ 8
Mert Yazıcı
Ok, collection can help. A little less direct than in my dream but heh 😅
Thanks !
+ 8
Thanks everybody, I could finally oneline it the way I wanted with your help 😊
https://code.sololearn.com/cRXco9kSV8rM/?ref=app
+ 8
__import__('itertools').groupby you can use this to decrease 7 chars and a line
+ 6
Oh, great !
Thank you Mert Yazıcı
+ 5
From the docs, "It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function)."
https://docs.python.org/3/library/itertools.html#itertools.groupby
+ 4
It seems that groupby takes only consecutive elements with same value of key function into one group.
When you have for example 'oo', 'll', 'r', 'e', 'nn'
oo and nn will be in one group, then the length's parity changes, so r and e are in another group, and nn goes into new group
+ 4
Haha, you're welcome! 😊
I'd probably just use two list comprehensions or a for loop.
+ 1
Wow this thread ended up doing great
0
method code util