定义一个名为 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']

python使用循环遍历
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- CSDN专家-天际的海浪 2022-05-26 19:29关注
你题目的解答代码如下:
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
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用