?887 2022-05-26 19:10 采纳率: 97.8%
浏览 33
已结题

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

  • 写回答

2条回答 默认 最新

  • 关注

    你题目的解答代码如下:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月3日
  • 已采纳回答 5月26日
  • 创建了问题 5月26日

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?