使用itertools.groupby()
函数,按照指定的键(例如第一个字母)对输入进行分组:
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
如果您的列表已经排序,可以省略
sorted()
调用。
itemgetter(0)
可调用对象将返回每个单词的第一个字母(索引为0的字符),然后
groupby()
将生成该键以及仅由保持相同键的那些项目组成的可迭代对象。在这种情况下,循环遍历
words
可以给您所有以相同字符开头的项。
>>> 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