python for if one liner

101 Views Asked by At

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
1

There are 1 best solutions below

0
On

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)