我有一个列表如下:
data = [
[u'2012-10-31', '20', 9801, '0', '0', '0', '0'],
[u'2012-10-31', '21', 9266, '0', '0', '0', '0'],
[u'2012-10-31', '22', 10526, '0', '0', '0', '0'],
[u'2012-10-31', '23', 9570, '0', '0', '0', '0'],
[u'2012-10-31', '1', 5256, '0', '0', '0', '0'],
[u'2012-10-31', '0', 5020, '0', '0', '0', '0'],
# and so on...
]
我需要先按日期排序,它是索引0,小时是索引1.如何在python中进行排序?
答案 0 :(得分:7)
import datetime as dt
def parse(date, hour):
return dt.datetime.strptime(date, '%Y-%m-%d').replace(hour = int(hour))
data = [[u'2012-10-31', '20', 9801, '0', '0', '0', '0'], [u'2012-10-31', '21', 9266, '0', '0', '0', '0'], [u'2012-10-31', '22', 10526, '0', '0', '0', '0'], [u'2012-10-31', '23', 9570, '0', '0', '0', '0'], [u'2012-10-31', '1', 5256, '0', '0', '0', '0'], [u'2012-10-31', '0', 5020, '0', '0', '0', '0'], [u'2012-10-31', '3', 6755, '0', '0', '0', '0'], [u'2012-10-31', '2', 5748, '0', '0', '0', '0'], [u'2012-10-31', '5', 7013, '0', '0', '0', '0'], [u'2012-10-31', '4', 7099, '0', '0', '0', '0'], [u'2012-10-31', '7', 6705, '0', '0', '0', '0'], [u'2012-10-31', '6', 7498, '0', '0', '0', '0'], [u'2012-10-31', '9', 7976, '0', '0', '0', '0'], [u'2012-10-31', '8', 7770, '0', '0', '0', '0'], [u'2012-10-31', '11', 7440, '0', '0', '0', '0'], [u'2012-10-31', '10', 7836, '0', '0', '0', '0'], [u'2012-10-31', '13', 8781, '0', '0', '0', '0'], [u'2012-10-31', '12', 7949, '0', '0', '0', '0'], [u'2012-10-31', '15', 13083, '0', '0', '0', '0'], [u'2012-10-31', '14', 10739, '0', '0', '0', '0'], [u'2012-10-31', '17', 16339, '0', '0', '0', '0'], [u'2012-10-31', '16', 15182, '0', '0', '0', '0'], [u'2012-10-31', '19', 12565, '0', '0', '0', '0'], [u'2012-10-31', '18', 16169, '0', '0', '0', '0']]
data.sort(key = lambda row: parse(row[0], row[1]))
for row in data:
print(row)
产量
[u'2012-10-31', '0', 5020, '0', '0', '0', '0']
[u'2012-10-31', '1', 5256, '0', '0', '0', '0']
[u'2012-10-31', '2', 5748, '0', '0', '0', '0']
...
[u'2012-10-31', '21', 9266, '0', '0', '0', '0']
[u'2012-10-31', '22', 10526, '0', '0', '0', '0']
[u'2012-10-31', '23', 9570, '0', '0', '0', '0']
注意:您也可以避免解析日期:
data.sort(key = lambda row: (row[0], int(row[1])))
就足够了。在这种特殊情况下,这可能会更简单,但一般情况下,您应该在需要订购时将日期解析为日期时间。