定义一个名为 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无用
悬赏问题
- ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
- ¥15 Python3.5 相关代码写作
- ¥20 测距传感器数据手册i2c
- ¥15 RPA正常跑,cmd输入cookies跑不出来
- ¥15 求帮我调试一下freefem代码
- ¥15 matlab代码解决,怎么运行
- ¥15 R语言Rstudio突然无法启动
- ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
- ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
- ¥15 用windows做服务的同志有吗