Skip to main content
 首页 » 编程设计

python之在 python 中使用嵌套循环计算元音

2025年05月04日12小虾米

在自学嵌套循环时,我遇到了一个我真的需要帮助的练习。该代码计算列表中名称中的元音,并在外循环完成后将其放入新列表中。这是我的代码:

def get_list_of_vowel_count(name_list): 
 
    vowels = "aeiouAEIOU" 
 
 
    count_list = [] 
    count = 0 
    for name in name_list: 
        for i in range(len(vowels)): 
            if vowels[i] in name: 
                count += 1 
        count_list += [count] 
        count = 0 
 
    return count_list 
 
def main(): 
 
    name_list = ["Mirabelle", "John","Kelsey","David","Cindy","Dick","aeeariiiosoisduuus"]  
    vowel_counts = get_list_of_vowel_count(name_list) 
    print(vowel_counts) 
 
main() 

输出:

[3, 1, 1, 2, 1, 1, 5]

我的代码算不上好.. 例如,名称 Kelsey 中的元音包含 2 个 e 但它只算 1。我认为 range( len(vowels)) 可能是问题所在,但我不太确定。我尝试在 SO 数据库上研究类似主题,但找不到我要搜索的内容。请帮助我正确编写此代码。非常感谢。

附言。使用 python 3.5

请您参考如下方法:

您不必费力学习 Python。这将是您的 Pythonic 解决方案

for name in name_list: 
    print (len([l for l in name if l in "aeiouAEIOU"]))