2017-11-05 1 views
0

아래 코드는 특정 문자로 시작하는 단어의 개수를 실행하도록되어 있지만 실행했을 때 개수는 0이어야합니다. { 'I' : 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)) 
관련 문제