gpt4 book ai didi

python - 计算每个元音出现的次数

转载 作者:行者123 更新时间:2023-11-28 19:46:52 24 4
gpt4 key购买 nike

我写了一个小程序来计算每个元音在列表中出现的次数,但它没有返回正确的计数,我不明白为什么:

vowels = ['a', 'e', 'i', 'o', 'u']
vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)
wordlist = ['big', 'cats', 'like', 'really']

for word in wordlist:
for letter in word:
if letter == 'a':
aCount += 1
if letter == 'e':
eCount += 1
if letter == 'i':
iCount += 1
if letter == 'o':
oCount += 1
if letter == 'u':
uCount += 1
for vowel, count in zip(vowels, vowelCounts):
print('"{0}" occurs {1} times.'.format(vowel, count))

输出是

"a" occurs 0 times.
"e" occurs 0 times.
"i" occurs 0 times.
"o" occurs 0 times.
"u" occurs 0 times.

但是,如果我在 Python shell 中键入 aCount,它会给我 2,这是正确的,所以我的代码确实更新了 aCount 变量并正确存储了它.为什么不打印正确的输出?

最佳答案

问题出在这一行:

vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)
如果稍后开始递增 aCount

vowelCounts 不会更新。

设置a = [b, c] = (0, 0)等同于a = (0, 0)[b, c] = (0, 0)。后者相当于设置b = 0c = 0

按如下方式重新排列您的逻辑,它将起作用:

aCount, eCount, iCount, oCount, uCount = (0,0,0,0,0)

for word in wordlist:
for letter in word:
# logic

vowelCounts = [aCount, eCount, iCount, oCount, uCount]

for vowel, count in zip(vowels, vowelCounts):
print('"{0}" occurs {1} times.'.format(vowel, count))

关于python - 计算每个元音出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50340232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com