2017-12-06 11 views
1

私はこの機能を解決する方法について正しいアイデアを持っていると思いますが、私は確信していません なぜdocstringに表示された結果が得られないのですか?誰でもこの問題を解決するのを助けてくれますか?辞書の単語の頻度を返します

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 
+0

'D [長さ] = {カウント}'間違いありませんあなたが欲しいもの。 –

+0

なぜですか?長さがキーであり、頻度であるcountが値です。 – bigez

+0

いいえ、長さがキーで、値は単一要素を含む* 'set' *です。これは周波数を表す' int'です。 –

答えて

0
あなたは今、元の要素の長さが含まれてい 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 

出力:間違いなくCounterを使用して

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

マップなしでそれを行う方法はありますか? – bigez

+0

これは 's'の各要素に対して' s'を繰り返し処理するので最適ではなく、 'O(n^2)'の実行時間を与えます。 – Sebastian

+0

@bigezなぜ 'map'を避けたいですか?あなたはそれをジェネレータ式に置き換えることができますが、無意味です。 – Sebastian

2

が最良の選択肢である:

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 
+0

通常通りに行う方法はありますか? – bigez

+0

通常は定義してください。これは、標準のPythonライブラリのみを使用します。あなたの問題は、何が起こっているのか分からないということであれば、初心者向けのPythonコースを受講することをお勧めします。 – Sebastian

+0

私は、初心者のものを使ってそれをどうすればいいのですか? – bigez

1

リスト内の任意の単語に対してループを実行するだけです。各反復の長さが、まだキーとして辞書にない場合、値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 
関連する問題