需要获取相关数组索引的元音计数

时间:2019-03-21 13:09:04

标签: python python-3.x

2

当我尝试执行此代码部分时,实际上什么也没显示出来,我需要计算“ HELLO”字的值

2 个答案:

答案 0 :(得分:1)

您可以将sum函数与生成器表达式一起使用,该表达式可遍历列表中每个单词的每个字母并测试该字母是否为元音:

def countVowels(candidateWords):
    return sum(letter in 'AEIOU' for word in candidateWords for letter in word)

答案 1 :(得分:1)

什么都不显示的主要原因是因为您在定义函数后尚未调用该函数。那里还有其他错误。

下面是正确的代码,用于打印单词列表中所有单词的元音计数:

candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RIPPLE', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY']
vowel=['A','E','I','O','U']

def countVowels(candidateWords):

    for index in range(len(candidateWords)):
        count=0
        for _ in candidateWords[index]:
            if _.upper() in vowel:
                count += 1
        print(candidateWords[index], 'has', count, 'vowels')

countVowels(candidateWords)