计算每个元音出现的次数

2024-10-01 19:17:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

输出是

^{pr2}$

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


Tags: inforifcountwordwordlistlettervowel
3条回答

问题在于这条线:

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

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

设置a = [b, c] = (0, 0)相当于a = (0, 0)和{}。后者相当于设置b = 0和{}。在

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

^{pr2}$

您还可以使用collections counter(这是计数事物时的自然go-to函数,它返回一个字典):

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

退货:

^{pr2}$

信笺:

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

您可以使用字典理解:

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}

输出:

^{pr2}$

相关问题 更多 >

    热门问题