python - 计算每个元音出现的次数
问题描述
我编写了一个小程序来计算每个元音出现在列表中的次数,但它没有返回正确的计数,我不明白为什么:
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.
但是,如果我aCount
在 Python shell 中键入,它会给我2
,这是正确的,所以我的代码确实更新了 aCount 变量并正确存储它。为什么不打印正确的输出?
解决方案
问题在于这一行:
vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)
vowelCounts
如果您稍后开始递增,则不会更新aCount
。
设置a = [b, c] = (0, 0)
等价于a = (0, 0)
和[b, c] = (0, 0)
。后者相当于设置b = 0
and c = 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))
推荐阅读
- g++ - 为什么 g++ 找不到 -I 包含路径中的预编译头文件?
- workflow - 使用 activiti 将工作流分配给 Alfresco 中的组
- python-3.x - Groupby 扩展计数 - 不同时间戳组的元素变化
- python - 如何使用自定义时区在 django 中根据时间过滤查询集?
- python - 如何生成一个随机数,将它们放入字典中,然后返回重复次数
- go - 在 helm 模板中将千兆字节转换为字节
- ios - 如何存储和访问 NSAttributedString.Key.foregroundColor 值的“数组”
- c - 为什么这个循环永远存在?
- java - 只需要更新java中mongo数组中的特定元素
- xml - 错误:文档中没有引用语法约束(DTD 或 XML 模式)