2017-11-05 12 views
0

以下のコードは、特定の文字で始まる単語の数を実行するはずですが、実行するとカウントは0になります。 :2、 'b':2、 't':3、 'f':1}。私はどんな助けにも感謝します。ありがとう!コードが正しく実行されていない

def initialLets(keyStr): 
     '''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper 
     and lower case letters should be considered different letters.''' 
     inLets = {} 
     strList = keyStr.split() 
     firstLets = [] 
     for words in strList: 
      if words[0] not in firstLets: 
       firstLets.append(words[0]) 
     for lets in firstLets: 
      inLets[lets] = strList.count(lets) 
     return inLets 

text = "I'm born to trouble I'm born to fate" 
print(initialLets(text)) 

答えて

4

あなたはこれを試すことができます。

text = "I'm born to trouble I'm born to fate" 
new_text = text.split() 
final_counts = {i[0]:sum(b.startswith(i[0]) for b in new_text) for i in new_text} 

出力:あなたが手紙ではなく、発生のその番号を追加して

{'I': 2, 'b': 2, 't': 3, 'f': 1} 
+1

辞書の理解は正しいことです –

0

あなたはカウンターを持っていません。

はそう簡単にする:

def initialLets(keyStr): 
     '''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper 
     and lower case letters should be considered different letters.''' 

     strList = keyStr.split() 

     # We initiate the variable that gonna take our results 
     result = {} 

     for words in strList: 
      if words[0] not in result: 
       # if first letter not in result then we add it to result with counter = 1 
       result[words[0]] = 1 
      else: 
       # We increase the number of occurence 
       result[words[0]] += 1 

     return result 

text = "I'm born to trouble I'm born to fate" 
print(initialLets(text)) 
0

を第一に、単語の最初の文字がでそれを置く前に、リストに含まれている場合は、チェックしているそれはちょうど1つだけ各文字の一覧を構成するになるだろう。第二に、あなたのstrListinLets[lets] = strList.count(lets)の代わりに各単語のリストです。inLets[lets] = firstLets.count(lets) ...あなたの現在のコードがこれを行う最もクリーンな方法ではありませんが、この小さな変更はうまくいきました。

def initialLets(keyStr): 
    '''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper 
    and lower case letters should be considered different letters.''' 
    inLets = {} 
    strList = keyStr.split() 
    firstLets = [] 
    for words in strList: 
     firstLets.append(words[0]) 
    for lets in firstLets: 
     inLets[lets] = firstLets.count(lets) 
    return inLets 

text = "I'm born to trouble I'm born to fate" 
print(initialLets(text)) 
関連する問題