【发布时间】:2025-12-28 00:05:06
【问题描述】:
试图在字典中使用.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'
它应该产生一个数字。怎么了?
【问题讨论】:
-
我猜
word是一个字符串,我在你的for循环中看到你有bigcount = word,所以现在bigcount也是一个字符串。下一次循环count > bigcount正在比较int和str。 -
我认为你的最后两个作业是倒退的。您将
int和str分配给了错误的变量。