0

How will I count the vowels of each string element in my list?

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
zero323
  • 322,348
  • 103
  • 959
  • 935
Angelos
  • 13
  • 5

3 Answers3

1

Here's a nested list comprehension that will achieve what you want:

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

This is equivalent to:

count = 0
for word in list:
    for char in word:
        if char.lower() in 'aeiou':
            count += 1
Rocky Li
  • 5,641
  • 2
  • 17
  • 33
0

This could be another way to find the vowels of each string element in your list.

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)

Output:

{'lola': 2, 'anna': 2, 'mary': 1}
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

You could use Python's filter() function to strip non vowels from the string and then get the length of the remaining string:

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

This would print:

2
2
1
Martin Evans
  • 45,791
  • 17
  • 81
  • 97