如何按照日期的字符串进行排序?
时间:2010-04-07 来源:blackjimmy
问题:
给定一个列表,按照日期进行排序:
l = [{'date': '2010-04-01','people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}]
解决1: import operator
l = [{'date': '2010-04-01','people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}]
sorted( l, key = operator.itemgetter('date') )
[{'date': '2010-04-01', 'hits': 4522, 'people': 1047}, {'date': '2010-04-02', 'hits': 3277, 'people': 736}, {'date': '2010-04-03', 'hits': 2582, 'people': 617}]
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}]
解决1: import operator
l = [{'date': '2010-04-01','people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}]
sorted( l, key = operator.itemgetter('date') )
[{'date': '2010-04-01', 'hits': 4522, 'people': 1047}, {'date': '2010-04-02', 'hits': 3277, 'people': 736}, {'date': '2010-04-03', 'hits': 2582, 'people': 617}]
解决2:
records = [
{'date': '2010-04-01', 'people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}
]
records.sort(key=lambda x: x['date'].split('-'))
相关阅读 更多 +