Python 为什么使用>;在这段代码中会产生错误吗?
正在尝试在字典中使用Python 为什么使用>;在这段代码中会产生错误吗?,python,counting,items,Python,Counting,Items,正在尝试在字典中使用.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 f
.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'
它应该产生一个数字。怎么了?你的作业倒过来了。您实际使用的是
。请正确获取
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
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigcount = count # Switched these two
bigword = word
如果您使用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]
如果您使用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]
我猜word
是一个字符串,我在for循环中看到了bigcount=word
,所以现在bigcount
也是一个字符串。下一次循环count>bigcount
是比较int
和str
。我认为你上两次的作业是反向的。您将int
和str
分配给了错误的变量。我猜word
是一个字符串,我在for循环中看到您有bigcount=word
,所以现在bigcount
也是一个字符串。下一次循环count>bigcount
是比较int
和str
。我认为你上两次的作业是反向的。您将int
和str
分配给了错误的变量。我尝试过切换您提到的变量,但仍然会产生相同的回溯。如果bigcount是None或bigcount>count,我尝试过切换你提到的那些,它仍然会产生相同的回溯。或者我做得不对。如果bigcount为None或bigcount>count