Python:根据单词的第一个字符拆分列表

kkih6yb8  于 2022-12-17  发布在  Python
关注(0)|答案(3)|浏览(219)

我有点被一个问题卡住了,我一直在绕圈子,直到我把自己弄糊涂了。
我想做的是列出一个单词表:

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

等等。
有简单的方法来做这件事吗?

sdnqo3pr

sdnqo3pr1#

使用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
lvjbypge

lvjbypge2#

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

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

wqsoz72f3#

定义拆分(n):对于n中的i,n2 = []:如果i[0]不在n2中:n2.附加(i[0])n2.排序()用于n中的j:z = j[0] z1 = n2.索引(z)n2.插入(z1+1,j)返回n2
word_list =[“是”、“有”、“做”、“说”、"得到“、”制造“、”去“、”知道“、”拿“、”看到“、”来“、”想“、”看“、”想要“、”给予“、”使用“、”查找“、”告诉“、”询问“、”工作“、”似乎“、”感觉“、”离开“、”呼叫“] print(split(word_list))

相关问题