【问题标题】:Returning frequencies of words in a dictionary返回字典中单词的频率
【发布时间】:2017-12-06 22:11:48
【问题描述】:

我认为我对如何解决此功能有正确的想法,但我不确定 为什么我没有得到文档字符串中显示的所需结果。谁能帮我解决这个问题?

def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps 
track of word length and frequency of length. Each key is a word length and 
the corresponding value is the number of words in the given list of that 
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a', 
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
    count = count + length
    d[length] = {count}
    count += 1
return d

【问题讨论】:

  • d[length] = {count} 绝对不是你想要的。
  • 为什么不呢?长度是键,频率是计数,是值。
  • 不,长度是key,value是一个set,包含一个元素,是一个int,代表频率。

标签: python python-3.x


【解决方案1】:

使用Counter 绝对是最好的选择:

In [ ]: from collections import Counter
   ...: d = Counter(map(len, s))
   ...: d == {1:2, 6:2, 8:1, 2:1, 10:1}
Out[ ]: True

不使用“花哨的东西”,我们使用生成器表达式,我认为它同样花哨:

Counter(len(i) for i in s)

如果“通常”是指使用 for 循环,我们可以这样做:

d = {}
for i in s:
    if len(i) not in d:
        d[len(i)] = 1
    else:
        d[len(i)] += 1

【讨论】:

  • 普通的有办法吗?
  • 普通定义。这仅使用标准 Python 库。如果您的问题是您根本不了解发生了什么,我建议您参加完整的 Python 初学者课程。
  • 我的意思是我们如何在 python 中使用初学者的东西来做到这一点?
  • 定义初学者的东西。 collections.Counter 是一个相对容易理解的东西,通过阅读它的文档来理解。
  • 输入是一个列表。
【解决方案2】:

只需对列表中的任何单词进行循环。在每次迭代中,如果长度不在字典中作为键,则创建值为 1 的新键,否则增加键的先前值:

def list_to_dict(word_list):
   d = dict()
   for any_word in word_list:
      length = len(any_word)  
      if length not in d:
          d[length] = 1
      else:
          d[length] += 1
   return d

【讨论】:

    【解决方案3】:

    您可以使用字典推导来迭代 s,它现在包含其原始元素的长度:

    s = ['A', 'little', 'sentence', 'to', 'create', 'a', 'dictionary']
    final_s = {i:len([b for b in s if len(b) == i]) for i in map(len, s)}
    

    输出:

    {1: 2, 6: 2, 8: 1, 2: 1, 10: 1}
    

    简单地说:

    new_d = {} 
    for i in s:
        new_d[len(i)] = 0
    for i in s:
        new_d[len(i)] += 1
    

    输出:

    {8: 1, 1: 2, 2: 1, 10: 1, 6: 2}
    

    【讨论】:

    • 有没有办法不用地图?
    • 这是次优的,因为它为s 中的每个元素迭代s,使其运行时间为O(n^2)
    • @bigez 为什么要避免使用map?你可以用生成器表达式替换它,但这没有意义。
    • 我想看看你是如何做到不使用花哨的东西的。
    • @bigez 查看我的答案。
    猜你喜欢
    • 2017-09-27
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    相关资源
    最近更新 更多