Python对Namedtuples列表进行排序

时间:2014-11-30 10:14:23

标签: python

我试图按time排序,我不知道从哪里开始。

[
    A(id=u'BLI52E', time=datetime.datetime(2014, 11, 30, 9, 52, 49, 209102)),
    A(id=u'DHCS4J', time=datetime.datetime(2014, 11, 30, 9, 53, 36, 495319)),
    A(id=u'4HMS4J', time=datetime.datetime(2014, 11, 30, 9, 53, 16, 395329)),
    A(id=u'GFTS4J', time=datetime.datetime(2014, 11, 30, 9, 53, 36, 295319)),
    A(id=u'BH244K', time=datetime.datetime(2014, 11, 30, 9, 53, 23, 591319)),
]

1 个答案:

答案 0 :(得分:2)

按"键排序"在列表中包含的命名元组中,您可以执行以下操作:

spam = [
            A(id=u'BLI52E', time=datetime.datetime(2014, 11, 30, 9, 52, 49, 209102)),
            A(id=u'DHCS4J', time=datetime.datetime(2014, 11, 30, 9, 53, 36, 495319))
       ]
spam.sort(key=lambda x:x.time)

从这里提取: Python: Tuples/dictionaries as keys, select, sort