1

我有一个看起来像这样的列表:

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 中做到这一点?

4

1 回答 1

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])))

就够了。在这种特殊情况下,这可能会更简单,但一般来说,当您想要订购日期时,您应该将日期解析为日期时间。

于 2012-11-09T11:15:52.360 回答