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

时间:2014-02-24 14:29:05

标签: 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

    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)

任何人都可以帮我编写满足上述条件的功能

1 个答案:

答案 0 :(得分:1)

由于您是初学者,我认为最好从普通循环和简单构造开始,而不是使用更复杂的库工具。

所以,这是我的函数版本:

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]

这几乎是你的算法,但是在一行中。您可以了解有关他们的更多信息here