python - 为什么在此代码中使用 > 会产生错误?
问题描述
试图.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'
它应该产生的是一个数字。怎么了?
解决方案
你的任务倒过来了。您实际上使用.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
推荐阅读
- git - 切换到管道内的另一个分支?
- java - 哪些 ClientConfiguration 设置最适合建立 Elasticsearch 连接
- google-apps-script - Google Apps 脚本 - Gmail - 是否可以将邮件作为附件转发?
- haskell - Haskell Monads 和 liftIO 我不明白
- python - pyglet 如何知道如何运行 on_draw() 函数?
- javascript - ExtJs 布局,时区显示在日期时间字段旁边
- kubernetes - 为什么 Kubernetes 不能直接与容器一起工作
- mysql - 如何仅在一行中使用 group by?
- sas - SAS 对特定值求和
- google-sheets - 如何将 Google Big Query 链接到 Google 表格?