计算数组中的元音

wom*_*daa 5 python arrays for-loop nested

我知道我快要弄清楚了,但我一直在绞尽脑汁,想不出这里出了什么问题。我需要计算nameList使用vowelList数组的数组中的元音数,目前它输出 22,这不是正确的元音数。

顺便说一句,22 是数组 nameList 长度的两倍,但我看不出我写的内容会输出数组长度的两倍的任何原因。任何帮助,将不胜感激。不是在寻找答案,而是在正确的方向上轻推。

nameList = [ "Euclid", "Archimedes", "Newton","Descartes", "Fermat", "Turing", "Euler", "Einstein", "Boole", "Fibonacci", "Nash"]
vowelList = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U','u']

z=0
counter = 0
for k in nameList:
    i = 0
    for q in vowelList:
        counter+=nameList[z].count(vowelList[i])
        i+=1
    z=+1
print("The number of vowels in the list is",counter)
Run Code Online (Sandbox Code Playgroud)

小智 4

你想得太难了。放松一下,让 Python 来完成工作:

nameList = [ "Euclid", "Archimedes", "Newton","Descartes", "Fermat", "Turing", "Euler", "Einstein", "Boole", "Fibonacci", "Nash"]
nameStr = ''.join(nameList).lower()
nVowels = len([c for c in nameStr if c in 'aeiou'])
print(f"The number of vowels in the list is {nVowels}.")
>>> The number of vowels in the list is 31.
Run Code Online (Sandbox Code Playgroud)

在 Python 中给猫剥皮的方法有很多:)