[Tutor] complex iteration over a list

Michele Alzetta michele.alzetta at aliceposta.it
Sat Jul 3 04:54:21 EDT 2004


Il ven, 2004-07-02 alle 20:51, Gregor Lingl ha scritto:

> Suggestion:
> Within your for-loop:
>      create a pair of names d, i which initially have the values day and 
> index
>      replace the 2 if-statements with a while loop that calculates the
>                  correct day number: you have to subtract months[i] from d
>                  as long as d > months[i] and subsequently increment i by 1
>                 (to use the next month in the next execution of the loop 
> body)
>      append d to daysinperiod

Hmm .. yes, I think that is what I was looking for, and it will come in
handy for another thing of the same sort I'll have to code in a while.
This particular problem though is more easily solved ! 
I've found that calendar is useless, but datetime.timedelta does it, as
my startday is a timedelta object (and so is my endday, which I had
changed to number of days thinking it would make things simpler).

startday = datetime(2004,6,1,8)
endday = datetime(2004,9,1,8)

def daysinperiod(startday,endday):
    daysinperiod = []
    while startday <= endday:
        daysinperiod.append(startday.day)
        startday = startday + timedelta(days=1)
    return daysinperiod

Eliminates the need for lists with the length of different months,
eliminates the nightmare of leap-years ...
Python is always simpler and more powerful than one thinks :-) 

-- 
Michele Alzetta <michele.alzetta at aliceposta.it>



More information about the Tutor mailing list