如何排序日期时间或日期对象的列表? [英] How do I sort a list of datetime or date objects?
本文介绍了如何排序日期时间或日期对象的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何排序日期和/或日期时间对象的列表?接受的答案此处对我无效:
How do I sort a list of date and/or datetime objects? The accepted answer here isn't working for me:
from datetime import datetime,date,timedelta
a=[date.today(), date.today() + timedelta(days=1), date.today() - timedelta(days=1)]
print a # prints '[datetime.date(2013, 1, 22), datetime.date(2013, 1, 23), datetime.date(2013, 1, 21)]'
a = a.sort()
print a # prints 'None'....what???
推荐答案
您正在获得无
因为 list.sort()
它运行就地,这意味着它不返回任何东西,而是修改列表本身。您只需要调用 a.sort()
,而不必将它分配到 a
。
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
有一个内置函数 sorted()
,它返回列表的排序版本 - a = sorted( a)
将会做你想要的。
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
这篇关于如何排序日期时间或日期对象的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文