Python sort 2-D list by time string

Posted by Mark Kennedy on Stack Overflow See other posts from Stack Overflow or by Mark Kennedy
Published on 2013-11-08T21:45:55Z Indexed on 2013/11/08 21:53 UTC
Read the original article Hit count: 171

Filed under:
|
|
|

How do I sort a multi dimensional list like this based on a time string? The sublists can be of different sizes (i.e. 4 and 5, here)

I want to sort by comparing the first time string in each sublist (sublist[-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])

The sorted result would be

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

I tried the following:

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

and it works but it doesn't respect the sublist size ordering

© Stack Overflow or respective owner

Related posts about python

Related posts about string