Python:根据单词的首字母拆分列表

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

有没有简单的方法来做到这一点?
3个回答

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()调用。 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

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'])

0

def split(n): n2 = [] for i in n: if i[0] not in n2: n2.append(i[0]) n2.sort() for j in n: z = j[0] z1 = n2.index(z) n2.insert(z1+1, j) return n2

word_list = ['be','have','do','say','get','make','go','know','take','see','come','think', 'look','want','give','use','find','tell','ask','work','seem','feel','leave','call'] print(split(word_list))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接