自学python:根据首字母对一组单词进行分类变成含列表的字典

 

words = ['apple', 'bat', 'bar', 'atom' , 'book']

by_letter = {}

for word in words:
    letter = word[0]   #letter = word的第一个字母,这里的word可以认为是一个列表,例如apple[0]=a
    if letter not in by_letter:   #如果letter(word[0])不在字典by_letter
        by_letter[letter] = [word]    #则k、v值为word[0],word加入到字典by_letter中
    else:
        by_letter[letter].append(word)    #如果letter(word[0])在字典by_letter,则将值word加入到字典by_letter中的关键值word[0]中

bt_letter #运行
{'a':['apple','atom'],'b':['bat','bar','book']}    #结果输出

 

版权声明:
作者:水东柳
链接:https://shuidl.com/2252.html
来源:水东柳博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>