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

2024-09-28 05:23:31 发布

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

import random
count=0

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

def countVowels(candidateWords):
    vowel=['A','E','I','O','U']

    for index in range (len(candidateWords)):

        if vowel in candidateWords[0]:
            count=count+1
            return count
            print(count)
        else:
            return False

当我试图执行这个代码部分时,实际上什么都不显示,我需要得到“HELLO”字的值的计数


Tags: nameinimporthelloreturncountrandompotato
2条回答

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

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

不显示任何内容的主要原因是定义函数后没有调用它。还有其他的错误

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

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)

相关问题 更多 >

    热门问题