Python按时间字符串排序2-D列表

时间:2013-11-08 21:45:56

标签: python string sorting numpy

如何根据时间字符串对这样的多维列表进行排序?子列表可以具有不同的大小(这里是4和5)

我想通过比较每个子列表中的第一个字符串(子列表[-4])

进行排序
x =  
(['1513', '08:19PM', '10:21PM', 1, 4],
['1290', '09:45PM', '11:43PM', 1, 4],
['0690', '07:25AM', '09:19AM', 1, 4],
['0201', '08:50AM', '10:50AM', 1, 4],
['1166', '04:35PM', '06:36PM', 1, 4],
['0845', '05:40PM', '07:44PM', 1, 4],
['1267', '07:05PM', '09:07PM', 1, 4],
['1513', '08:19PM', '10:21PM', 1, 4],
['1290', '09:45PM', '11:43PM', 1, 4],
['8772', '0159', '12:33PM', '02:43PM', 1, 5],
['0888', '0570', '09:42PM', '12:20AM', 1, 5],
['2086', '2231', '04:10PM', '06:20PM', 1, 5])

排序后的结果将是

sortedX = 
    (['0690', '07:25AM', '09:19AM', 1, 4],
    ['0201', '08:50AM', '10:50AM', 1, 4],
    ['1166', '04:35PM', '06:36PM', 1, 4],
    ['0845', '05:40PM', '07:44PM', 1, 4],
    ['1267', '07:05PM', '09:07PM', 1, 4],
    ['1513', '08:19PM', '10:21PM', 1, 4],
    ['1513', '08:19PM', '10:21PM', 1, 4],
    ['1290', '09:45PM', '11:43PM', 1, 4],
    ['1290', '09:45PM', '11:43PM', 1, 4],
    ['8772', '0159', '12:33PM', '02:43PM', 1, 5], 
    ['2086', '2231', '04:10PM', '06:20PM', 1, 5],
    ['0888', '0570', '09:42PM', '12:20AM', 1, 5])

我尝试了以下内容:

sortedX = sorted(x, key=lambda k : k[-4])   #k[-4] is the first time string

并且它有效但它不遵守子列表大小排序

2 个答案:

答案 0 :(得分:3)

按字符串比较时间可能有问题,因为字符串按字典顺序进行比较:

>>> '02:00PM' > '12:00PM'
False
>>> '2' > '100'
True

因此,请先使用time.strptime将这些时间字符串转换为时间对象。

>>> import time
>>> import pprint
def func(x):
    return (len(x), time.strptime(x[-4], '%I:%M%p'))
... 
>>> pprint.pprint(sorted(x, key=func))
[['0690', '07:25AM', '09:19AM', 1, 4],
 ['0201', '08:50AM', '10:50AM', 1, 4],
 ['1166', '04:35PM', '06:36PM', 1, 4],
 ['0845', '05:40PM', '07:44PM', 1, 4],
 ['1267', '07:05PM', '09:07PM', 1, 4],
 ['1513', '08:19PM', '10:21PM', 1, 4],
 ['1513', '08:19PM', '10:21PM', 1, 4],
 ['1290', '09:45PM', '11:43PM', 1, 4],
 ['1290', '09:45PM', '11:43PM', 1, 4],
 ['8772', '0159', '12:33PM', '02:43PM', 1, 5],
 ['2086', '2231', '04:10PM', '06:20PM', 1, 5],
 ['0888', '0570', '09:42PM', '12:20AM', 1, 5]]

要按多个值排序,请使用元组,在您的情况下,第一项是长度和时间对象作为第二项。

答案 1 :(得分:0)

如果您想按多个特征排序,请使用元组,并按优先级顺序按每个特征排序。

sortedX = sorted(x, key=lambda k : (len(k), k[-4]))