为什么在此代码中使用 > 会产生错误?
Why do the use of > in this code produce an error?
正在尝试使用字典中的 .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
如果你使用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]
正在尝试使用字典中的 .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
如果你使用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]