python使用循环遍历

定义一个名为 build_dictionary(words_list) 的函数,该函数将单词列表作为参数。该函数通过循环遍历列表中的每个元素并创建相应的键:值项来创建字典。键由整数组成,值是小写的唯一单词列表,其中每个单词的长度等于键值。
注意:
您可以假设参数words_list中的单词中没有标点字符(即只有字母)。但是,您应该将所有单词转换为小写。
您可以假定该文件仅包含唯一的单词。
每个单词列表必须按升序排序
输入:data = ['The', 'heavy', 'rain', 'is', 'to', 'ease', 'tonight', 'however', 'further', 'showers', 'Are', 'expected', 'tomorrow']
a_dict = build_dictionary(data)
for key in sorted(a_dict):
print(key, a_dict[key])
输出:
2 ['is', 'to']
3 ['are', 'the']
4 ['ease', 'rain']
5 ['heavy']
7 ['further', 'however', 'showers', 'tonight']
8 ['expected', 'tomorrow']
输入:
data = ['ist', 'tea', 'eye', 'the', 'ant', 'ten', 'Ted', 'age', 'dog', 'CAT', 'red']
a_dict = build_dictionary(data)
for key in sorted(a_dict):
print(key, a_dict[key])
输出:
3 ['age', 'ant', 'cat', 'dog', 'eye', 'ist', 'red', 'tea', 'ted', 'ten', 'the']

你题目的解答代码如下:

def build_dictionary(words_list):
    dic = {}
    for v in words_list:
        k = len(v)
        dic.setdefault(k,[]).append(v.lower())
    for k,v in dic.items():
        v.sort()
    return dic

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632