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

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.

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

最佳答案

问题在于这一行:

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 = 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))

10-06 12:03