[英]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) 子列表可以具有不同的大小(即此处为4和5)
I want to sort by comparing the first time string in each sublist (sublist[-4]) 我想通过比较每个子列表(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. 因此,使用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]]
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]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.