创建一个字典,其中键是一个整数,值是一个随机句子的长度

新手上路,请多包涵

这里是 python 的超级新手,我已经为这段代码苦苦挣扎了一段时间。基本上,该函数返回一个以整数作为键的字典,值是所有单词,其中单词的长度与每个键相对应。

到目前为止,我能够创建一个字典,其中的值是每个单词的总数,而不是实际单词本身。

所以传递以下文本

"the faith that he had had had had an affect on his life"

到函数

def get_word_len_dict(text):
    result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0}
    for word in text.split():
        if str(len(word)) in result_dict:
            result_dict[str(len(word))] += 1
    return result_dict

回报

1 - 0
2 - 3
3 - 6
4 - 2
5 - 1
6 - 1

我需要输出的地方:

 2 - ['an', 'he', 'on']
3 - ['had', 'his', 'the']
4 - ['life', 'that']
5 - ['faith']
6 - ['affect']

我想我需要将值作为列表返回。但我不确定如何处理它。

原文由 Brian 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 643
1 个回答

您的代码正在计算每个单词长度的出现次数 - 但不存储单词本身。

除了将每个单词捕获到具有相同大小的单词列表之外,您似乎还想要:

  1. 如果未表示单词长度,则不要返回该长度的空列表 - 只是没有该长度的键。
  2. 每个单词列表中没有重复项
  3. 每个单词列表都已排序

集合容器非常适合积累单词 - 集合自然会消除添加到其中的任何重复项。

使用 defaultdict(sets) 将设置一个空的集合字典——只有在检查每个单词的循环中引用字典键时才会创建字典键。

 from collections import defaultdict

def get_word_len_dict(text):

    #create empty dictionary of sets
    d = defaultdict(set)

    # the key is the length of each word
    # The value is a growing set of words
    # sets automatically eliminate duplicates
    for word in text.split():
        d[len(word)].add(word)

    # the sets in the dictionary are unordered
    # so sort them into a new dictionary, which is returned
    # as a dictionary of lists

    return {i:sorted(d[i]) for i in d.keys()}

在您的示例字符串中

a="the faith that he had had had had an affect on his life"

像这样调用函数:

 z=get_word_len_dict(a)

返回以下列表:

 print(z)
{2: ['an', 'he', 'on'], 3: ['had', 'his', 'the'], 4: ['life', 'that'], 5: ['faith'], 6: ['affect']}

字典中每个值的类型都是“列表”。

 print(type(z[2]))
<class 'list'>

原文由 blackeneth 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题