P
P
PILITYXXX1232020-08-16 01:17:48
Python
PILITYXXX123, 2020-08-16 01:17:48

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

2 answer(s)
D
Dimonchik, 2020-08-16
@PILITYXXX123

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])

well, or +1 with a check for the end of the list

Z
zexer, 2020-08-16
@zexer

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 question

Ask a Question

731 491 924 answers to any question