【发布时间】:2018-10-24 16:46:31
【问题描述】:
我编写了一个小程序来计算每个元音出现在列表中的次数,但它没有返回正确的计数,我不明白为什么:
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分配给一个零元组。它与变量没有任何关系,也没有办法做到这一点。你最好在循环之后分配给它。 -
只需使用
collections.counter。 -
谜题的一部分:考虑
foo = bar = 0。foo和bar都等于零也就不足为奇了。在vowelCounts = [aCount, eCount, iCount, oCount, uCount] = (0,0,0,0,0)中,python使用pythons [sequence unpacking](docs.python.org/3/tutorial/…)规则将(0,0,0,0,0)分配给[aCount, eCount, iCount, oCount, uCount],同时还将(0,0,0,0,0)分配给vowelCounts。如果你打印vowelCounts,你会注意到它是一个元组而不是一个列表。 -
文体点。不要以这种方式使用多重赋值:
a = b = (1, 2, 3)。它非常不可读,并导致难以跟踪错误(如果您不知道在哪里查看),例如此处的错误。
标签: python python-3.x list for-loop