简体   繁体   English

返回字典中单词的频率

[英]Returning frequencies of words in a dictionary

I think I have the right idea on how to solve this function, but I'm not sure why I don't get the desired results shown in the docstring. 我想我对如何解决这个函数有正确的想法,但我不确定为什么我没有得到文档字符串中显示的所需结果。 Can anyone please help me fix this? 有人可以帮我解决这个问题吗?

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

Using Counter definitely is the best option: 使用Counter肯定是最好的选择:

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

Without using "fancy stuff", we use generator expressions, something I consider to be equally fancy: 在不使用“花哨的东西”的情况下,我们使用生成器表达式,我认为它同样有点奇特:

Counter(len(i) for i in s)

If by "ordinarily" you mean using for loops, we can do that like so: 如果“通常”意味着使用for循环,我们可以这样做:

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

Simply do a loop for any word in the list. 只需对列表中的任何单词执行循环。 In each iteration create new key with value 1 if the length is not in the dict as a key yet, otherwise increase the previous value for the key: 在每次迭代中,如果长度不在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

You can use dictionary comprehension to iterate over s , which now contains the length of its original elements: 您可以使用字典理解来迭代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)}

Output: 输出:

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

Simply: 只是:

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

Output: 输出:

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

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

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