问题描述
我有一个时间列表和当前时间.我试图找到距离当前时间最近和最远的时间.我发现很难用字符串来解决这些任务.
I've got a list of times and a current time. I'm trying to find the closest and furthest time to the current time. I find it difficult to solve such tasks in strings.
但是,我可以使用 min 和 max 函数打印字符串列表中的最小和最大时间.
However, I can print the minimum and maximum time in the list of strings using min and max functions.
我看到@kennytm 使用以下方法发布了类似的问题解决方案:min(myList, key=lambda x:abs(x-myNumber))
,但我不完全确定这是否适用于字符串.
谁能为我的问题提供解决方案?
Can anyone provide a solution to my question?
current_time = '09:00'
time = ['09:30','11:50','11:55','11:55','12:00','12:10','12:15','12:25','12:35','12:50','12:55', '13:00']
print(min(time))
# 09:30
print(max(time))
# 13:00
推荐答案
将 hh:mm 格式转换为单个整数,用于当前时间和时间列表.然后遍历整数,并使用原始时间列表跟踪时间.
Convert the hh:mm format to a single integer, for the current time and the list of times. Then iterate through the integers, and track the times using the original list of time.
def hhmm2int(t):
hour_min = t.split(':')
hours_as_minutes = int(hour_min[0]) * 60
minutes = int(hour_min[1])
return hours_as_minutes + minutes
current_time = '09:00'
time = ['09:30', '11:50', '11:55', '11:55', '12:00', '12:10', '12:15', '12:25', '12:35', '12:50', '12:55', '13:00']
current_time = hhmm2int(current_time)
time_as_int = [hhmm2int(t) for t in time]
min_delta = float('inf')
max_delta = 0
closest_time = ''
furthest_time = ''
for i in range(len(time_as_int)):
delta = abs(time_as_int[i] - current_time)
if delta < min_delta:
min_delta = delta
closest_time = time[i]
if delta > max_delta:
max_delta = delta
furthest_time = time[i]
print(closest_time, furthest_time)
这篇关于查找与字符串列表最接近和最远的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!