返回python中按元音计数过滤的列表

返回python中按元音计数过滤的列表,python,list,Python,List,返回一个列表,该列表仅包含输入列表中包含至少计数元音的单词 def filter_by_vowel_count(input, count): result = [] for word in input: if sum(p in 'aeiou' for p in word) == count: result.append(word) return result pass as

返回一个列表,该列表仅包含输入列表中包含至少计数元音的单词

    def filter_by_vowel_count(input, count):
        result = []
        for word in input:
           if sum(p in 'aeiou' for p in word) == count:
            result.append(word)
        return result
      pass

    assert  [] == filter_by_vowel_count(["engine", "hello", "cat", "dog", "why"], 5)
    assert  ["engine"] == filter_by_vowel_count(["engine", "hello", "cat", "dog", "why"], 3)
    assert  ["hello", "engine"] == filter_by_vowel_count(["hello", "engine", "cat", "dog", "why"], 2)
    assert  ["hello", "engine", "dog", "cat"] == filter_by_vowel_count(["hello", "engine", "dog", "cat", "why"], 1)
    # even capital vowels are vowels :)
    assert  ["HELLO", "ENGINE", "dog", "cat"] == filter_by_vowel_count(["HELLO", "ENGINE", "dog", "cat", "why"], 1)
    assert  ["HELLO", "ENGINE", "dog", "cat", "why"] == filter_by_vowel_count(["HELLO", "ENGINE", "dog", "cat", "why"], 0)

有人能帮我编写满足上述条件的函数吗

既然你是初学者,我认为最好从普通循环和简单构造开始,而不是从更复杂的库工具开始

这是我的函数版本:

def filter_by_vowel_count(inp, count):  # We changed input to inp as input is a special function in Python

    ret = []  # The list to return
    for word in inp:
        total = 0  # The total nubmer of vowels
        for letter in word:
            if letter in 'aeiouAEIOU':  # Note that some letters might be in capital
                total += 1
        if total >= count:
            ret.append(word)
    return ret
您的问题是在使用本应使用的
=
时使用了
=
。下面是使用列表理解的更好版本:

def filter_by_vowel_count(inp, count):

    return [word for word in inp if sum(1 for p in word if p in 'aeiouAEIOU') >= count]

这基本上是你的算法,但只有一行。你可以进一步了解他们。

@FredrikPihl很乐意效劳:)