嵌套for循环以通过迭代字符串和列表来匹配元音

时间:2016-06-11 00:36:01

标签: python python-3.x for-loop

我正在尝试遍历列表,并将该列表中的每个字符与字符串中的字符匹配:

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

为每个元音返回"a" occurs 2 times.但这不起作用。我做错了什么?

3 个答案:

答案 0 :(得分:2)

在这里使用collections.Counter可能是最pythonic方式,也避免嵌套for循环

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

输出:

a occurs 2 times
e occurs 2 times
i occurs 2 times
o occurs 0 times
u occurs 0 times

答案 1 :(得分:0)

这是一个有效的版本:

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

请注意,j是一个可怕的名称,它应该是vowel

答案 2 :(得分:0)

试试这个:

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

结果:

a occurs 2 times
e occurs 2 times
i occurs 2 times
o occurs 0 times
u occurs 0 times