计算完整字符串列表中的元音数量(Python)

时间:2018-10-28 16:30:56

标签: python string counting

如何计算列表中每个字符串元素的元音?

list = ['lola', 'anna','mary']
count = 0
for w in list:
    if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
        count=count+1
    print count

3 个答案:

答案 0 :(得分:1)

这是一个嵌套的列表理解功能,可以实现您想要的功能:

count = len([e for x in list for e in x if e.lower() in 'aeiou'])

这等效于:

count = 0
for word in list:
    for char in word:
        if char.lower() in 'aeiou':
            count += 1

答案 1 :(得分:0)

这可能是查找列表中每个字符串元素的元音的另一种方法。

def countvowel(str):
        num_vowel = 0
        for char in str:
            if char in "aeiouAEIOU":
               num_vowel = num_vowel + 1
        return num_vowel

    list = ['lola', 'anna','mary']
    vowel_count = {}
    for str in list:
        vowel_count[str] = countvowel(str)

    print(vowel_count)

输出:

{'lola': 2, 'anna': 2, 'mary': 1}

答案 2 :(得分:0)

您可以使用Python的filter()函数从字符串中去除非元音,然后获取剩余字符串的长度:

for test in ['lola', 'anna', 'mary']:
    print(len(list(filter(lambda x: x in 'AEIOUaeiou', test))))

这将打印:

2
2
1