我刚刚开始使用Python,并想知道如何对此进行排序
从最早的时间到最晚的时间列出。
('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')
感谢任何帮助。
答案 0 :(得分:2)
仅在带有标准库的python3中:
import time
hours = ('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')
format = '%I:%M%p'
time_hours = [time.strptime(t, format) for t in hours]
result = [time.strftime(format, h) for h in sorted(time_hours)]
assert result == ['07:00AM', '12:00PM', '02:00PM', '05:00PM', '08:45PM']
答案 1 :(得分:1)
答案 2 :(得分:1)
如果时间总是采用该格式,您可以将时间分成子部分。
x = "12:30PM"
# Use python's string slicing to split on the last two characters
time, day_half = x[:-2], x[-2:]
# Use python's string.split() function to get the difference between hours and minutes
# Because "11" < "2" for strings, we need to convert them to integers
hour, minute = [int(t) for t in time.split(":")]
# Get the remainder because 12 should actually be 0
hour = hour % 12
# Output it as a tuple, which sorts based on each element from left to right
sortable = (day_half, hour, minute)
#: ("PM", 12, 30)
要将其全部包装起来,请使用以下内容:
def sortable_time(time_str):
time, day_half = time_str[:-2], time_str[-2:]
hour, minute = [int(t) for t in time.split(":")]
hour = hour % 12
return day_half, hour, minute
# When sorting, use `key` to define the method we're sorting with
# (The returned list however, will be filled with the original strings)
result = sorted(your_time_list, key=sortable_time)
#: ['7:00AM', '12:00PM', '2:00PM', '5:00PM', '8:45PM']
如果您不能保证最后有两个字母,或者中间是冒号,那么您最好使用像Prune建议的库。
答案 3 :(得分:0)
您所展示的内容不是一个时间列表,而是一个字符串元组。元组是不可变的,不能被排序,只有像列表这样的可变集合才可以。首先,您需要将元组转换为列表:
times = ['5:00PM','2:00PM','7:00AM','8:45PM','12:00PM']
您现在可以尝试对此列表进行排序,但字符串不会按预期方式排序。相反,您需要创建一个自定义排序函数,将临时将列表中的值转换为struct_time
个对象并使用这些对象进行排序。
import time
time_format = '%I:%M%p' # match hours, minutes and AM/PM
def compare_as_time(time_str1, time_str2):
# parse time strings to time objects
time1 = time.strptime(time_str1, time_format)
time2 = time.strptime(time_str2, time_format)
# return comparison, sort expects -1, 1 or 0 to determine order
if time1 < time2:
return -1
elif time1 > time2:
return 1
else:
return 0
现在你可以调用sorted()
并传入你的列表和你的自定义比较函数,然后你会得到一个字符串列表,按照这些字符串中的时间排序:
sorted_times = sorted(times, compare_as_time)
Python 3注意事项:上一个示例假设使用Python 2.如果您使用的是Python 3,则需要将比较功能转换为key function
。这可以使用functools.cmp_to_key()
完成,如下所示:
form functools import cmp_to_key
sorted_times = sorted(times, key=cmp_to_key(compare_as_time))