0

我在第 9 行不断收到一个键错误,我终其一生都无法弄清楚。

这是我的代码

numbers = (input("Enter numbers separated by spaces > "))
alist = []
alist = numbers.split()
count = {}
for word in alist:
    if word not in alist:
        (count[word]) = 1
    else:
        (count[word]) = (count[word]) + 1
print(count)
for k,v in count.item():
    if v == 1:
        print(k, "occurs", v, "time")
    else:
        print(k, "occurs", v, "times")
4

1 回答 1

1

word not in alist总是假的,因为 for 循环遍历alist.

替换以下行:

if word not in alist:

if word not in count:

顺便说一句,您不需要 . 周围的括号count[word]

于 2013-11-15T06:45:51.717 回答