如何在python

时间:2016-01-20 07:41:34

标签: python list sorting time

我有以下列表表示列车的到达和出发时间。

arr  = ['9:00',  '9:40', '9:50',  '11:00', '15:00', '18:00']
dep  = ['9:10', '12:00', '11:20', '11:30', '19:00', '20:00']

我想合并和排序它们。我做了以下。

final = sorted(arr+dep)

输出:

['11:00', '11:20', '11:30', '12:00', '15:00', '18:00', '19:00', '20:00', '9:00', '9:10', '9:40', '9:50']

预期输出:(时间戳的实际排序)

['9:00', '9:10', '9:40', '9:50','11:00', '11:20', '11:30', '12:00', '15:00', '18:00', '19:00', '20:00']

如何实现预期的输出?

2 个答案:

答案 0 :(得分:6)

字符串按字典顺序排序。 '9:00'将在'11:00'之后出现,因为对于字符串,'9'大于'1'

要解决此问题,您可能希望拆分':'并从值中创建整数:

def sort_key(time):
    hour, minute = time.split(':')
    return int(hour), int(minute)

arr  = ['9:00',  '9:40', '9:50',  '11:00', '15:00', '18:00']
dep  = ['9:10', '12:00', '11:20', '11:30', '19:00', '20:00']
sorted(arr + dep, key=sort_key)

答案 1 :(得分:4)

试试这个

>>> import datetime
>>> arr  = ['9:00',  '9:40', '9:50',  '11:00', '15:00', '18:00']
>>> dep  = ['9:10', '12:00', '11:20', '11:30', '19:00', '20:00']
>>> sorted(dep+arr, key=lambda x: datetime.datetime.strptime(x, '%H:%M'))
['9:00', '9:10', '9:40', '9:50', '11:00', '11:20', '11:30', '12:00', '15:00', '18:00', '19:00', '20:00']