4

我有点卡在一个问题上,我一直在绕着它转,直到我把自己弄糊涂了。

我想要做的是列出单词列表:

['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

ETC...

有没有简单的方法可以做到这一点?

4

2 回答 2

11

用于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()调用。callable 将返回每个单词的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
于 2013-06-28T14:18:51.670 回答
1

而不是使用任何库导入或任何花哨的东西。这是逻辑:

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'])
于 2018-05-01T16:43:56.213 回答