[英]Finding the closest and furthest value to a list of strings
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.
我发现很难在字符串中解决此类任务。
However, I can print the minimum and maximum time in the list of strings using min and max functions.但是,我可以使用 min 和 max 函数在字符串列表中打印最小和最大时间。
I saw @kennytm posting a similar solution to the problem using:
min(myList, key=lambda x:abs(x-myNumber))
, but I'm not entirely sure if that works on strings.我看到@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
When you convert the dates to a datetime
object you can get the closest time with min(time,key=lambda x : abs(current_time-x))
:当您转换日期为
datetime
对象,你可以得到的最接近时间min(time,key=lambda x : abs(current_time-x))
from datetime import datetime
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']
def get_time(time):
return datetime.strptime(time, '%H:%M')
current_time = get_time(current_time)
time = [get_time(i) for i in time]
print(min(time,key=lambda x : abs(current_time-x)).strftime('%H:%M'))
Convert the hh:mm format to a single integer, for the current time and the list of times.将 hh:mm 格式转换为单个整数,用于当前时间和时间列表。 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)
A simple solution:一个简单的解决方案:
diff_time = lambda t: abs(int(current_time.replace(':', '')) \
- int(t.replace(':', '')))
From 00:00 (int: 0) to 23:59 (int: 2359), time is already lexicographical ordered and the order is maintained while converting to integer.从 00:00 (int: 0) 到 23:59 (int: 2359),时间已经是按字典顺序排列的,并且在转换为整数时保持顺序。
>>> min(time, key=diff_time)
'09:30'
>>> max(time, key=diff_time)
'13:00'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.