计算每个元音出现的次数

时间:2018-05-14 23:08:45

标签: python python-3.x list for-loop

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

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变量并正确存储它。为什么不打印正确的输出?

4 个答案:

答案 0 :(得分:6)

问题在于这一行:

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

答案 1 :(得分:4)

你也可以使用集合计数器(在计算事物时它是自然的首选函数,它返回一个字典):

from collections import Counter

vowels = list('aeiou')
wordlist = ['big', 'cats', 'like', 'really']

lettersum = Counter(''.join(wordlist))

print('\n'.join(['"{}" occurs {} time(s).'.format(i,lettersum.get(i,0)) for i in vowels]))

返回:

"a" occurs 2 time(s).
"e" occurs 2 time(s).
"i" occurs 2 time(s).
"o" occurs 0 time(s).
"u" occurs 0 time(s).

lettersum:

Counter({'l': 3, 'a': 2, 'e': 2, 'i': 2, 'c': 1, 'b': 1, 
         'g': 1, 'k': 1, 's': 1, 'r': 1, 't': 1, 'y': 1})

答案 2 :(得分:1)

您可以使用词典理解:

vowels = ['a', 'e', 'i', 'o', 'u']
wordlist = ['big', 'cats', 'like', 'really']
new_words = ''.join(wordlist)
new_counts = {i:sum(i == a for a in new_words) for i in vowels}

输出:

{'a': 2, 'e': 2, 'i': 2, 'o': 0, 'u': 0}

答案 3 :(得分:0)

除了@jpp所说的 像整数这样的简单数据类型是按值而不是通过引用返回的 所以当你把它分配给某个东西并改变它不受影响的东西时

a = 10
b = a #b=a=10
b = 11 #b=11, a=10
print a, b
--> 10 11

我已经对他做了评论,但我需要声誉:D