簡體   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