Python:基于单词第一个字符的拆分列表

2024-06-14 17:58:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点纠结在一个问题上,我绕来绕去,直到我把自己搞糊涂了。在

我想做的是列出一个单词:

['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'Biblical', 'Bill', 'Billgone']

然后按字母顺序排列:

^{pr2}$

等等。。。在

有没有简单易行的方法?在


Tags: andasall单词areataboutalso
2条回答

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

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

使用^{}按特定键(如第一个字母)将输入分组:

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处的字符),然后{}将生成该键加上一个iterable,该iterable只包含那些键保持不变的项。在本例中,这意味着在words上循环将为您提供以相同字符开头的所有项。在

演示:

^{pr2}$

相关问题 更多 >