简体   繁体   中英

Python sort 2-D list by time string

How do I sort a multi dimensional list like this based on a time string? The sublists can be of different sizes (ie 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

Comparing time by strings can be buggy, as strings are compared lexicographically:

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

So, use time.strptime to convert those time string to time objects first.

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

And to sort by multiple values use a tuple, in your case first item being the length and time object as the second item.

如果要按一个以上特征进行排序,请使用一个元组,并按优先级对每个特征进行排序。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM