计算每个元音出现的次数

Jim*_*616 2 python for-loop list python-3.x

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

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))
Run Code Online (Sandbox Code Playgroud)

输出是

"a" occurs 0 times.
"e" occurs 0 times.
"i" occurs 0 times.
"o" occurs 0 times.
"u" occurs 0 times.
Run Code Online (Sandbox Code Playgroud)

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

jpp*_*jpp 6

问题出在这一行:

vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)
Run Code Online (Sandbox Code Playgroud)

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

设置a = [b, c] = (0, 0)相当于a = (0, 0)[b, c] = (0, 0).后者相当于设置b = 0c = 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))
Run Code Online (Sandbox Code Playgroud)