根据对象的时间戳值对对象进行排序

时间:2018-10-25 19:56:42

标签: python python-2.7

我有一个具有多个值的对象。时间戳是其领域之一。创建对象时,我已将输入字符串转换为时间戳。

DATETIME_FORMAT = '%d-%b-%y %H.%M.%S.%f %p'

class CustomObject:
    def __init__(self, input_data):
        entry_list = [entry.strip() for entry in input_data.split(',')]
        self.field_one = entry_list[0]
        self.field_two = entry_list[1]
        self.field_timestamp = datetime.strptime(entry_list[2], DATETIME_FORMAT)

我想根据CustomObjectfield_timestamp进行排序。我该怎么办?

我当时在看sorted函数,但它使用lambda作为表达式。在这种情况下,我没有表达式,我只有一个要用于排序的字段。应该怎么做?

1 个答案:

答案 0 :(得分:1)

sorted_list = sorted(list_of_CustomObject, key=lambda x: x.field_timestamp)

但实际上您应该使用成员访问方法,而不要使用公开的成员变量。

相关问题