在python中,对日期字段进行排序,字段有时可能为null

Wes*_*Wes 22 python sorting

我很难想出一个灵巧的方法来处理这种情况.我从数据库读回来的数据.我想对accoutingdate进行评论.但是,accoutingdate有时可能为空.我目前正在做以下事情:

results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=True)
Run Code Online (Sandbox Code Playgroud)

但是,由于一些accoutingdates为null,这种炸弹的"TypeError:无法将datetime.date与NoneType进行比较".

什么是"最正确"或"最恐怖"的方式来处理这个问题?

Ale*_*lli 30

使用key=函数绝对是正确的,您只需要决定如何处理None值 - 选择一个datetime您想要视为等于None排序目的的值.例如:

import datetime
mindate = datetime.date(datetime.MINYEAR, 1, 1)

def getaccountingdate(x):
  return x['accountingdate'] or mindate

results = sorted(results, key=getaccountingdate, reverse=True)
Run Code Online (Sandbox Code Playgroud)

只是看看这比定义一个cmp函数简单得多- 如果你做一些基准测试,你会发现它也明显更快!使用cmp函数代替此key函数没有任何优势,这样做是一个糟糕的设计选择.


sth*_*sth 11

您可以使用None专门处理的自定义排序功能:

def nonecmp(a, b):
  if a is None and b is None:
    return 0
  if a is None:
    return -1
  if b is None:
    return 1
  return cmp(a, b)

results = sorted(results, cmp=nonecmp, ...)
Run Code Online (Sandbox Code Playgroud)

这被视为None小于所有日期时间对象.