开发者

Sort Python list of objects by date

开发者 https://www.devze.com 2023-02-12 17: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 birthda开发者_开发知识库te is a datetime

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 birthda开发者_开发知识库te is a datetime object.

I would like to order the list by birthdate with the oldest first. What is the most Pythonic way to do this?


results.sort(key=lambda r: r.person.birthdate)


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

精彩评论

暂无评论...
验证码 换一张
取 消