我编写了一个小程序来计算每个元音在列表中出现的次数,但是它没有返回正确的计数,我不明白为什么:
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))
输出是
^{pr2}$但是,如果我在pythonshell中输入aCount
,它会给我2
,这是正确的,因此我的代码确实更新了aCount变量并正确地存储了它。为什么它不能打印正确的输出?在
问题在于这条线:
如果稍后开始递增
aCount
,则vowelCounts
不会更新。在设置}。后者相当于设置}。在
a = [b, c] = (0, 0)
相当于a = (0, 0)
和{b = 0
和{重新排序您的逻辑如下,它将工作:
^{pr2}$您还可以使用collections counter(这是计数事物时的自然go-to函数,它返回一个字典):
退货:
^{pr2}$信笺:
您可以使用字典理解:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐