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



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

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数据库上搜索类似的主题,但找不到我要搜索的内容。请帮助我正确编写此代码。非常感谢。

ps。使用python 3.5

您不必在Python上下功夫。这将是你的Python解决方案

for name in name_list:
    print (len([l for l in name if l in "aeiouAEIOU"]))
if vowels[i] in name:
    count += 1

对任何数量的事件都只加一。相反,你可以做

count += name.count(vowels[i])

您还可以迭代字符串中的字符,如下所示:

for vowel in vowels:
    # use vowel

在蟒蛇的神奇世界里,还有一些可能的"简化":

def get_list_of_vowel_count(name_list):
    vowels = "aeiouAEIOU"
    for name in name_list:
        yield sum([name.count(vowel) for vowel in vowels])

或者采用其neo的解决方案:

def get_list_of_vowel_count(name_list):
    vowels = "aeiouAEIOU"
    for name in name_list:
        yield len([c for c in name if c in vowels])

yield基本上只是指"附加到返回的列表中"。它消除了手动填写列表并稍后返回列表的需要。

如果你出于某种原因想发疯,你也可以把外循环放在列表理解中:

def get_list_of_vowel_count(name_list):
    return [len([c for c in name if c in "aeiouAEIOU"])
                for name in name_list]
def get_list_of_vowel_count(name_list):
    return [[name.count(v) for v in "aeiouAEIOU"] for name in name_list]

最新更新