首页 > 解决方案 > 为什么在此代码中使用 > 会产生错误?

问题描述

试图.get在字典中使用该功能。

我没有尝试太多,因为我还不知道那么多。

name = input("Enter file: ")
handle = open(name)
counts = dict()
for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word, 0) + 1

bigcount = None
bigword = None
for word, count in counts.items():
    if bigcount is None or count > bigcount:
        bigcount = word
        bigword = count

我得到这个结果:

 if bigcount is None or count > bigcount:
TypeError: '>' not supported between instances of 'int' and 'str'

它应该产生的是一个数字。怎么了?

标签: pythoncountingitems

解决方案


你的任务倒过来了。您实际上使用.get正确。

bigcount = None
bigword = None
for word, count in counts.items():
    if bigcount is None or count > bigcount:
        bigcount = count     # Switched these two
        bigword = word

推荐阅读