在一个数组中计算元音字母数量

5
我知道我离解决这个问题很近了,但我一直在努力思考,却想不出哪里有问题。我需要使用vowelList数组来计算nameList数组中元音字母的数量,目前输出的是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)

3
您正在重复使用变量k,请选择一个不同的名称。 - MattDMo
你使用的是哪个 代码编辑器 - moctarjallo
我投票关闭此问题,因为这是拼写错误:将z = +1更改为z += 1,然后您的代码就可以了。 - Mad Physicist
我通过基本的调试找到了这个问题:当你在每次迭代时打印 nameList[z] 时,你会发现它一遍又一遍地添加 Archimedes 中的元音字母。 - Mad Physicist
@MadPhysicist 哇,你说得完全正确。不过,我真的很感谢所有的评论和回复,它们帮助我理解如何更有效地使用Python循环。 - wombatpandaa
显示剩余5条评论
2个回答

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.

Python有很多种方式解决问题 :)


1
这并没有解释代码中的错误。除了一些奇怪的循环外,我认为它相当易读且符合 Python 风格。OP 的代码在打字错误之前都是正确的。 - Mad Physicist
真的没错!我只想补充一点,(在我看来)有很多别名的冗长代码会为这种错误创造更多机会。 - Rohan S Byrne

1
这里有一些更易理解的内容:
nameList = [ "Euclid", "Archimedes", "Newton","Descartes", "Fermat", "Turing", "Euler", "Einstein", "Boole", "Fibonacci", "Nash"]
vowelList = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U','u']


counter = 0
for name in nameList:
    for char in name:
        for vowel in vowelList:
            if char == vowel:
                counter += 1
print("The number of vowels in the list is",counter)

列表中元音字母的数量为31


在我看来,这比 OP 的两个循环难以理解。使用 in 运算符可以帮助你摆脱循环而不会牺牲可读性。 - Mad Physicist
1
我是指比他们得到的答案更易理解。否则,我会建议使用一行代码 sum(i in 'aeiouAEIOU' for j in nameList for i in j) - Stab
我会将那个字符串用 set 包装起来。 - Mad Physicist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接