按日期对Python对象列表进行排序(当某些对象没有时)

按日期对Python对象列表进行排序(当某些对象没有时),python,list,sorting,Python,List,Sorting,这是对我以前工作的一个轻微更新 我有一个名为results的Python列表。结果列表中的大多数结果对象都有person对象,大多数person对象都有birthdate属性(result.person.birthdate)。生日是一个日期时间对象 我想按出生日期排列结果列表,最年长的排在第一位。但是,如果没有person对象或者person对象没有生日,我仍然希望结果包含在结果列表中。在列表的末尾将是理想的 做这件事最像蟒蛇的方式是什么 import datetime results.sort

这是对我以前工作的一个轻微更新

我有一个名为results的Python列表。结果列表中的大多数结果对象都有person对象,大多数person对象都有birthdate属性(result.person.birthdate)。生日是一个日期时间对象

我想按出生日期排列结果列表,最年长的排在第一位。但是,如果没有person对象或者person对象没有生日,我仍然希望结果包含在结果列表中。在列表的末尾将是理想的

做这件事最像蟒蛇的方式是什么

import datetime
results.sort(key=lambda r: r.person.birthdate
    if (r and r.person and r.person.birthdate)
    else datetime.datetime.now())
(请注意,您可以编辑上一个问题。)

我将“如果没有person对象或person对象没有生日”解释为如果结果对象没有“person”属性,同样,result.person对象也没有“birthdate”属性。然而,我注意到您前面的问题使用了奇怪的术语,如“person object set to None”(在注释中)。如何将对象设置为“无”?你是说person属性设置为None吗?当你问一个问题时,(1)请使其独立,(2)充分解释你的实际数据结构

import datetime
large_date = datetime.datetime(9999, 12, 31)
results.sort(key=lambda result:
    result.person.birthdate 
    if hasattr(result, 'person') and hasattr(result.person, 'birthdate')
    else large_date
    )
在这里可能有用:

from datetime import datetime

def key(result, default=datetime.max):
    try:
         return result.person.birthday or default
    except AttributeError:
         return default

results.sort(key=key)

提取项目中没有键的列表,并将其添加到排序列表中

haystack = [x for x in haystack if x[date_key] is None] + sorted([x for x in haystack if x[date_key] is None], key=lambda x: x[date_key])

我将“没有该名称的属性”解释为实际上有一个属性,但它没有。如果该属性实际上不存在,请将“XXX.name为None”更改为“nothasattr(XXX,name”)。您引用的是什么?你在哪里看到OP问题中提到的“属性”这个词?@John Machin:我已经解释过了。谢谢。我没有更新原件,因为我认为在我有正确答案后开始添加新的要求可能会令人困惑。考虑使用<代码> DATESTIME.DATEIME.MAX而不是<代码> DATETIME.DATETIME.NOW()/代码>它读得更干净。
haystack = [x for x in haystack if x[date_key] is None] + sorted([x for x in haystack if x[date_key] is None], key=lambda x: x[date_key])