代码之家  ›  专栏  ›  技术社区  ›  Wes

在python中,日期字段排序,字段有时可能为空。

  •  22
  • Wes  · 技术社区  · 15 年前

    我很难想出一个巧妙的方法来处理这类问题。我有从数据库读取回来的数据。我想整理账目。但是,accountingDate有时可能为空。我目前正在做以下工作:

    results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=True)
    

    但是,由于某些计算数据为空,此炸弹带有“typeerror:无法将datetime.date与nonetype进行比较”。

    处理这个问题的“最正确”或“最蟒蛇”方法是什么?

    2 回复  |  直到 15 年前
        1
  •  29
  •   Alex Martelli    15 年前

    使用A key= 功能是绝对正确的,你只需要决定你想如何治疗 None 值--选择 datetime 要将其视为 没有 用于排序。例如。:

    import datetime
    mindate = datetime.date(datetime.MINYEAR, 1, 1)
    
    def getaccountingdate(x):
      return x['accountingdate'] or mindate
    
    results = sorted(results, key=getaccountingdate, reverse=True)
    

    看看这比定义一个 cmp 相反,如果你做一些基准测试,你会发现它也明显更快!使用 凸轮轴位置 函数而不是这个 key 函数,这样做将是一个糟糕的设计选择。

        2
  •  11
  •   sth    15 年前

    您可以使用一个自定义排序函数来处理 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, ...)
    

    这样对待 没有 小于所有日期时间对象。