Answer the question
In order to leave comments, you need to log in
How can I find the closest Python value in a list?
There is a list -
a = ['2020-07-30', '2020-07-31', '2020-07-31', '2020-07-31', '2020-08-04', '2020-08' -05', '2020-08-06', '2020-08-06', '2020-08-08', '2020-08-08']
And there are 2 variables
b = '2020-07-27'
c = '2020-08-07'
It is necessary to write in the variable b1 the closest value to the variable b from the list, that is, 2020-07-30 or 2020-08-08 does not matter.
And in the variable c1 write the closest value to the variable c from the list, that is - 2020-08-06 or
Answer the question
In order to leave comments, you need to log in
ab = a[:]
ac = a[:]
ab.append(b)
ac.append(c)
ab.sort()
ac.sort()
ab_index = ab.index(b)-1 if ab.index(b) > 0 else 0
ac_index = ac.index(c)-1 if ac.index(c) > 0 else 0
print(ab[ab_index])
print(ac[ac_index])
import datetime
def convert_string_to_date(string: str):
return datetime.datetime.strptime(string, '%Y-%m-%d').date()
def get_near_date(date, date_list):
date_list_desc = sorted(date_list, reverse=True)
first_try = [date > i for i in date_list_desc]
if True in first_try:
return date_list_desc[first_try.index(True)]
date_list_asc = sorted(date_list, reverse=False)
second_try = [date < i for i in date_list_asc]
if True in second_try:
return date_list_asc[second_try.index(True)]
a = ['2020-07-30', '2020-07-31', '2020-07-31', '2020-07-31', '2020-08-04', '2020-08-05', '2020-08-06', '2020-08-06', '2020-08-08', '2020-08-08']
a = [convert_string_to_date(i) for i in a]
b = convert_string_to_date('2020-07-27')
c = convert_string_to_date('2020-08-07')
print(get_near_date(b, a))
# 2020-07-30
print(get_near_date(c, a))
# 2020-08-06
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question