我如何在我的函数中使用count()函数?

时间:2020-01-25 17:33:36

标签: python

我做了一个过滤字符串中元音的功能。

def number_of_vowels(stringPara):
    vowels = ['u', 'e', 'o', 'a', 'i']
    return list(filter(lambda x: x in vowels, stringPara))
print(number_of_vowels("Technical University"))    

现在,我需要通过count()函数对字符串包含的每个元音进行计数。但是我不知道当我有lambda函数时如何使用它。

4 个答案:

答案 0 :(得分:1)

def number_of_vowels(stringPara):
    vowels = ['u', 'e', 'o', 'a', 'i']
    return len(list(filter(lambda x: x in vowels, stringPara)))
print(number_of_vowels("Technical University"))

这是您要找的吗?

答案 1 :(得分:1)

您可以为此使用Counter

from collections import Counter

counter = Counter("Technical University")
vowels = ['u', 'e', 'o', 'a', 'i']

print({k: v for k, v in counter.items() if k in vowels})
# {'e': 2, 'i': 3, 'a': 1}

答案 2 :(得分:0)

它返回总计数和每个元音的计数:

def number_of_vowels(stringPara):
    vowels = ['u', 'e', 'o', 'a', 'i']
    f = list(filter(lambda x: x in vowels, stringPara))
    return(len(f), {v: f.count(v) for v in vowels if f.count(v)>0})

print(number_of_vowels("Technical University"))

答案 3 :(得分:0)

怎么样?

from collections import Counter


def numberOfVowels(param):
    vowels = {'a', 'e', 'i', 'o', 'u'}
    result = list(filter(lambda x: x in vowels, param))
    return result, dict(Counter(result))


print(numberOfVowels('Technical University'))


# Output:
# (['e', 'i', 'a', 'i', 'e', 'i'], {'e': 2, 'i': 3, 'a': 1})
相关问题