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

2024-05-18 15:18:49 发布

您现在位置: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函数时,我不知道如何使用它


Tags: oflambda函数字符串innumberreturndef
3条回答
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"))

这就是你要找的吗

您可以使用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}

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

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"))

相关问题 更多 >

    热门问题