首页 > 解决方案 > 计算每个元音出现的次数

问题描述

我编写了一个小程序来计算每个元音出现在列表中的次数,但它没有返回正确的计数,我不明白为什么:

vowels = ['a', 'e', 'i', 'o', 'u']
vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)
wordlist = ['big', 'cats', 'like', 'really']

for word in wordlist:
    for letter in word:
        if letter == 'a':
            aCount += 1
        if letter == 'e':
            eCount += 1
        if letter == 'i':
            iCount += 1
        if letter == 'o':
            oCount += 1
        if letter == 'u':
            uCount += 1
for vowel, count in zip(vowels, vowelCounts):
    print('"{0}" occurs {1} times.'.format(vowel, count))

输出是

"a" occurs 0 times.
"e" occurs 0 times.
"i" occurs 0 times.
"o" occurs 0 times.
"u" occurs 0 times.

但是,如果我aCount在 Python shell 中键入,它会给我2,这是正确的,所以我的代码确实更新了 aCount 变量并正确存储它。为什么不打印正确的输出?

标签: pythonpython-3.xlistfor-loop

解决方案


问题在于这一行:

vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)

vowelCounts如果您稍后开始递增,则不会更新aCount

设置a = [b, c] = (0, 0)等价于a = (0, 0)[b, c] = (0, 0)。后者相当于设置b = 0and c = 0

重新排序您的逻辑如下,它将起作用:

aCount, eCount, iCount, oCount, uCount = (0,0,0,0,0)

for word in wordlist:
    for letter in word:
        # logic 

vowelCounts = [aCount, eCount, iCount, oCount, uCount]

for vowel, count in zip(vowels, vowelCounts):
    print('"{0}" occurs {1} times.'.format(vowel, count))

推荐阅读