我试图寻找这个问题的答案,但没有成功。 (顺便说一句,我 15 岁,基本上刚开始使用 Python) 这是我的程序:
all = []
count = {}
line = input("Enter line: ")
while line:
word = line.split()
line = input("Enter line: ")
for w in word:
if w in count:
count[w] += 1
else:
count[w] = 1
for word in sorted(count):
print(word, count[word])
这是我得到的答案:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 1
我应该在什么时候得到:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 2
witch 1
拜托,有人可以帮忙吗?
最佳答案
for w in word:
循环在while line:
循环外执行。这意味着首先为每个 line
生成单个 word
列表,然后跳过每个这样的列表 end executes for w in word:
only for last 单词
列表。
要修复它,请更改 whoole for w in word:
循环的缩进(这一行和下面的 4 行)。向右移动 4 个空格。
all = []
count = {}
line = input("Enter line: ")
while line:
print("line is :" + line )
word = line.split()
line = input("Enter line: ")
for w in word:
if w in count:
count[w] += 1
else:
count[w] = 1
for word in sorted(count):
print(word, count[word])
是因为indentation in python is used to determine grouping of statements .
关于python - 字计数器(编程导论2(python)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283207/