代码运行不正常

时间:2017-11-05 00:02:43

标签: python

我下面的代码应该运行以某个字母开头的单词数,但是当我运行它时,计数都是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))

3 个答案:

答案 0 :(得分:4)

你可以试试这个:

dotnet test

输出:

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}

答案 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))

答案 2 :(得分:0)

首先,您要检查单词的第一个字母是否在列表中之前是否在列表中。这只会使列表中只包含每个字母中的1个。其次,您的strList是每个单词的列表,而不是inLets[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))