将整数与无类型进行比较

时间:2020-01-22 14:24:16

标签: python python-3.x

这是我教科书中的一个问题,您在其中创建了一个程序,该程序可以对文本文件中的电子邮件进行直方图处理(它们始终是第二个单词)。

handle = open("mbox-short.txt")

senders = {}
for line in handle:
    if line.startswith('From'):
        emails = line.split()
        if len(emails) < 3: continue
        email = emails[1]
        senders[email] = senders.get(email , 0) + 1

bigsender = None 
bigcount = None
for sender,times in senders.items():
    if bigcount < times:
        bigcount = times
        bigsender = sender    

print(bigsender, bigcount)

但是当我运行它时,它会产生一个错误:

TypeError: '<' not supported between instances of 'NoneType' and 'int'

当我将最后一个条件更改为:

if bigcount is None or bigcount < times:

我们是否仍在将bigcount与时间进行比较,我不知道发生了什么变化?

这是文本文件:https://www.py4e.com/code3/mbox-short.txt

1 个答案:

答案 0 :(得分:0)

if bigcount is None or bigcount < times时有两个独立的条件:bigcount is Nonebigcount < times。如果我们按顺序进行,则bigcount is None被评估为true。因为bigcount < times不可能取任何可能使整行错误的值(因为true or some_boolean对于some_boolean的任何可能值始终为true),所以评估短路和不会评估第二条语句,因此永远不会有机会产生类型错误。

换句话说,bigcount < times会产生错误,因为您无法比较bigcounttimes,但是在您的第二个示例中,从未评估任何代码。

相关问题