繁体   English   中英

返回字典中单词的频率

[英]Returning frequencies of words in a dictionary

我想我对如何解决这个函数有正确的想法,但我不确定为什么我没有得到文档字符串中显示的所需结果。 有人可以帮我解决这个问题吗?

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

使用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

只需对列表中的任何单词执行循环。 在每次迭代中,如果长度不在dict中作为键,则创建值为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

您可以使用字典理解来迭代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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM