我有点卡在一个问题上,我已经四处走动,直到我迷惑自己。
我要做的是取一个单词列表:
['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone']
然后按字母顺序对它们进行排序:
A
About
Absolutely
After
B
Bedlam
Behind
等...
有没有简单的方法可以做到这一点?
答案 0 :(得分:9)
使用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)
callable将返回每个单词的第一个字母(索引0处的字符),然后groupby()
将生成该键加上一个只包含密钥保持不变的项目的iterable 。在这种情况下,这意味着循环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
答案 1 :(得分:0)
而不是使用任何库导入,或任何花哨的东西。 这是逻辑:
def splitLst(x):
dictionary = dict()
for word in x:
f = word[0]
if f in dictionary.keys():
dictionary[f].append(word)
else:
dictionary[f] = [word]
return dictionary
splitLst(['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone'])