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

时间:2014-01-25 13:39:26

标签: python string list

我需要编写一个函数,通过按元音计数过滤来返回列表。

我试过这个,但输出不正确:

def filter_by_vowel_count(input, count):

    for words in input:
        for p in words:
            if p in 'aeiou':
                value +=1
                if value == count:
                    list1.append(words)

5 个答案:

答案 0 :(得分:2)

使用sum和生成器表达式:

>>> def filter_by_vowel_count(words, count):
...     result = []
...     for word in words:
...         if sum(p in 'aeiou' for p in word) == count:
...             result.append(word)
...     return result
...
>>> fruits = ['banana', 'apple', 'lemon', 'pineapple', 'coconut']
>>> filter_by_vowel_count(fruits, 2)
['apple', 'lemon']
>>> filter_by_vowel_count(fruits, 3)
['banana', 'coconut']

答案 1 :(得分:0)

你的问题是缩进,重置和返回:

for words in input:
    value = 0 # reset vowel count
    for p in words:
        if p in 'aeiou':
            value +=1
    if value == count: # should be outside for loop
        list1.append(words)
return list1 # return the new list

正如其他人所指出的那样,还有更简洁的方法可以达到你想要的效果。

答案 2 :(得分:0)

words = [] # list of strings
vowels = "aeiou"
filter(lambda x: sum(x.count(c) for c in vowels) == count, words )

答案 3 :(得分:0)

使用正则表达式:

import re
def filter( ls, c ):
    find = [ (s,len(re.findall("[aeiou]", s))) for s in ls ]
    return [ x for x in find if x[1] == c ]

fruits = ['banana', 'apple', 'lemon', 'pineapple', 'coconut']
print filter(fruits, 2)
print filter(fruits, 3)

输出:

[('apple', 2), ('lemon', 2)]
[('banana', 3), ('coconut', 3)]

答案 4 :(得分:0)

我可以使用内置的collections.Counter类来极大地简化您的生活:

from collections import Counter

def filter(fruits, num):
    num_of_vowels = [sum([c[k] for k in 'aeiou']) for c in [Counter(f) for f in fruits]] 
    return [f for i,f in enumerate(fruits) if num_of_vowels[i]==num]