【问题标题】:Why do the use of > in this code produce an error? [closed]为什么在此代码中使用 > 会产生错误? [关闭]
【发布时间】: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 正在比较 intstr
  • 我认为你的最后两个作业是倒退的。您将 intstr 分配给了错误的变量。

标签: python counting items


【解决方案1】:

如果你使用collections.Counter而不是重新实现它,你将没有机会犯这样的错误。

from collections import Counter


counts = Counter()
name = input("Enter file: ")
with open(name) as handle:
    for line in handle:
        counts.update(line.split())

bigword, bigcount = counts.most_common(1)[0]

【讨论】:

    【解决方案2】:

    你的作业倒过来了。你实际上正确地使用了.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
    

    【讨论】:

    • 我已经尝试切换你提到的那些,它仍然会产生相同的回溯。或者我做的不对。
    • 如果 bigcount 为 None 或 bigcount > count
    最近更新 更多