Search code examples
pythonloopsfor-loopincrementpython-xarray

How to increment iterator in loop with if condition?


I have a xarray data array which I would like to reassign by year to a dictionary. I unable to get the increment right since the code only correctly gets the date for the first 3 years (up to the first leap year). I tried dropping all the leap years so I could only have an increment of 365, however, I encountered memory errors thereafter.

pre={}
start=-365
for i in np.arange(1982,2020):
    if not i in leap_years:
        start+=365
        pre[i]=precip[start:start+365]
    else:
        start+=365
        pre[i]=precip[start:start+366]

Solution

  • The way you are using start, you need to increment once more after setting pre[i] for a leap year.

    pre={}
    start=-365
    for i in np.arange(1982,2020):
        if not i in leap_years:
            start+=365
            pre[i]=precip[start:start+365]
        else:
            start+=365
            pre[i]=precip[start:start+366]
            start+=1

    You can simplify this to

    start = 0
    for i in np.arange(1982, 2020):
        days_in_year = 365 if i not in leap_years else 366
        # days_in_year = 365 + int(i in leap_years)
        pre[i] = precip[start:start+days_in_year]
        start += days_in_year