Python: Sort list by date?

社会主义新天地 提交于 2020-01-30 13:15:34

问题


Is it possible to sort this list by date? It is for a flot graph so it has to be organized in this format of a list of smaller list pairs. I would like to be able to sort it by date.

[["2014-5-29", 19], ["2014-5-28", 16], ["2014-5-30", 20], ["2014-5-23", 16], ["2014-5-22", 1225], ["2014-5-21", 114], ["2014-5-20", 69], ["2014-5-27", 10], ["2014-5-31", 17], ["2014-5-25", 18], ["2014-5-24", 19], ["2014-5-26", 18], ["2014-6-2", 19], ["2014-6-1", 19], ["2014-5-18", 4], ["2014-5-19", 27]]

Thanks!


回答1:


Here is one way:

In [9]: l = [["2014-5-29", 19], ["2014-5-28", 16], ["2014-5-30", 20], ["2014-5-23", 16], ["2014-5-22", 1225], ["2014-5-21", 114], ["2014-5-20", 69], ["2014-5-27", 10], ["2014-5-31", 17], ["2014-5-25", 18], ["2014-5-24", 19], ["2014-5-26", 18], ["2014-6-2", 19], ["2014-6-1", 19], ["2014-5-18", 4], ["2014-5-19", 27]]

In [10]: sorted(l, key=lambda (date, _): map(int, date.split('-')))
Out[10]: 
[['2014-5-18', 4],
 ['2014-5-19', 27],
 ['2014-5-20', 69],
 ['2014-5-21', 114],
 ['2014-5-22', 1225],
 ['2014-5-23', 16],
 ['2014-5-24', 19],
 ['2014-5-25', 18],
 ['2014-5-26', 18],
 ['2014-5-27', 10],
 ['2014-5-28', 16],
 ['2014-5-29', 19],
 ['2014-5-30', 20],
 ['2014-5-31', 17],
 ['2014-6-1', 19],
 ['2014-6-2', 19]]


来源:https://stackoverflow.com/questions/24002449/python-sort-list-by-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!