Sort Python list of objects by date

前端 未结 2 1144
陌清茗
陌清茗 2020-12-28 12:43

I have a Python list called results. Each result in the results list has a person object, and each person object has a birthdate (result.person.birthdate). The birthdate is

相关标签:
2条回答
  • 2020-12-28 13:12
    results.sort(key=lambda r: r.person.birthdate)
    
    0 讨论(0)
  • 2020-12-28 13:18

    Totally agree with Amber, but there is another way of sorting by attribute (from the wiki: https://wiki.python.org/moin/HowTo/Sorting):

    from operator import attrgetter
    sorted_list = sorted(results, key=attrgetter('person.birthdate'))
    

    This method can actually be even faster than sorting with lambda

    0 讨论(0)
提交回复
热议问题