-1

I am trying to loop over a list, and match each character in that list with characters in a string:

wordlist = ['big', 'cats', 'like', 'really']
vowels = "aeiou"
count = 0
 for i in range(len(wordlist)):
    for j in vowels:
        if j in wordlist[i]:
            count +=1
            print(j,'occurs', count,'times')

to return "a" occurs 2 times. for each vowel but this does not work. What am i doing wrong?

AJP
  • 47
  • 10

3 Answers3

2

Using a collections.Counter here is probably the most pythonic way and also avoids nested for loops

import collections
vowels = "aeiou"
wordlist = ['big', 'cats', 'like', 'really']

letters = collections.Counter("".join(wordlist))
for letter in vowels:
    print(letter, "occurs", letters.get(letter, 0), "times")

This outputs:

a occurs 2 times
e occurs 2 times
i occurs 2 times
o occurs 0 times
u occurs 0 times
Keatinge
  • 4,264
  • 6
  • 23
  • 40
0

Here's a working version:

wordlist = ['big', 'cats', 'like', 'really']
vowels = "aeiou"
for j in vowels:
    count = 0
    for i in range(len(wordlist)):
        if j in wordlist[i]:
            count += 1
    print(j, 'occurs', count, 'times')

Note that j is a terrible name, it should really be vowel.

Alex Hall
  • 33,530
  • 5
  • 49
  • 82
0

Try this:

wordlist = ['big', 'cats', 'like', 'really']
vowels = "aeiou"        
for v in vowels:
    count = 0
    for word in wordlist:
        if v in word:
            count += 1
    print(v,'occurs', count, 'times')

results:

a occurs 2 times
e occurs 2 times
i occurs 2 times
o occurs 0 times
u occurs 0 times
juanpa.arrivillaga
  • 77,035
  • 9
  • 115
  • 152