int对象不可迭代?

时间:2014-11-19 06:35:34

标签: string python-3.x dictionary

我正在尝试创建一个程序,该程序将接受用户输入,该输入将是一串数字并打印出每个数字出现的次数。但是,我收到一个TypeError,声明int对象不可迭代?我该如何解决这个问题,为什么会发生这种情况?谢谢。

def main():
count = {}
user_input = input("Enter numbers separated by spaces: ")
for number in user_input.split():
    if number in count:
        count[number] = count[number] + 1
    else:
        count[number] = 1
print(count)

for k,v in count.values():
    if v == 1:
        print(k,"occurs one time")
    else:
        print(k,"occurs",v,"times")
main()

2 个答案:

答案 0 :(得分:1)

对于每个键,检查其值如下:

for key in count:
    if count[key] == 1:
        print(key,"occurs one time")
    else:
        print(key,"occurs",count[key],"times")

count.values()方法仅返回values中的dictionary而不是keyscount.items()会返回key value对。

答案 1 :(得分:1)

替换:

for k,v in count.values():

使用:

for k,v in count.items():

对于您的循环,您需要密钥k和值vcount.values()将仅返回 值。相比之下,count.items()将返回两者。