Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python for if one liner

I have an issue.

I want to make my code simple and more comprehensible.

I'm trying to get the next date's value from data x.

Here is my code. Is there a way to make it shorter using lambda or map?

def nextDay(date,x,time=1):
     res, c = None, 0

     while c<time:
          temp = iter(x)
          for key in temp:
               if key == date:
                    res = next(temp, None)
          date = res
          c+=1
     return res

x = {'2020-01-11': 3.4, '2020-01-13': 4.1, '2020-02-02': 4.1 }
print(x[nextDay('2020-01-11', x, time=1)])

Output:

4.1
like image 718
Juyun Lee Avatar asked Jul 18 '26 06:07

Juyun Lee


1 Answers

Instead of going through the dates time times and always only advancing by one date, just search the given date and then read the next time dates.

def nextDay(date, x, time=1):
    it = iter(x)
    date in it
    for _ in range(time):
        date = next(it, None)
    return date

Or with itertools.islice:

def nextDay(date, x, time=1):
    it = iter(x)
    date in it
    return next(islice(it, time - 1, None), None)
like image 190
superb rain Avatar answered Jul 20 '26 19:07

superb rain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!