Python: Split a list based on the first character of a word

I was kind of stuck in a problem, and Ive walked around until I embarrassed myself.

What I'm trying to do is take a list of words:

['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone'] 

Then sort them under and in alphabetical order:

 A About Absolutely After B Bedlam Behind 

etc...

Is there an easy way to do this?

+4
source share
1 answer

Use itertools.groupby() to group your input with a specific key, such as the first letter:

 from itertools import groupby from operator import itemgetter for letter, words in groupby(sorted(somelist), key=itemgetter(0)): print letter for word in words: print word print 

If your list is already sorted, you can omit the sorted() call. The called itemgetter(0) returns the first letter of each word (character with index 0), and groupby() will return this key plus iterability, consisting only of those elements for which the key remains unchanged. In this case, this means that looping over words gives you all the elements starting with the same character.

Demo:

 >>> somelist = ['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone'] >>> from itertools import groupby >>> from operator import itemgetter >>> >>> for letter, words in groupby(sorted(somelist), key=itemgetter(0)): ... print letter ... for word in words: ... print word ... print ... A About Absolutely After Aint Alabama AlabamaBill All Also Amos And Anyhow Are As At Aunt Aw B Bedlam Behind Besides Biblical Bill Billgone 
+8
source

Source: https://habr.com/ru/post/1488697/


All Articles