[Tutor] seek and slice a range in a list of dates

Kent Johnson kent37 at tds.net
Sun Feb 10 14:20:24 CET 2008


washakie wrote:
> Yes, I'm using 2.4, and will not likely be able to upgrade... so, the final,
> as you suggested Kent:
> 
>   
> dates_dt=([datetime.datetime(int(dates_list[i][0][:4]),int(dates_list[i][0][4:6]),
>                                
> int(dates_list[i][0][6:8]),int(dates_list[i][0][8:10]),
>                                
> int(dates_list[i][0][10:12]),int(dates_list[i][0][12:]))
>                                 for i in range(len(dates_list))])  

You don't need the outermost parentheses here.

> 
>    TstartNew=sorted(dates_dt,key=lambda d: abs(Tstart - d))[0]
>    Tstart_i=dates_dt.index(TstartNew)
>    TendNew=sorted(dates_dt, key=lambda d: abs(Tend -d))[0]
>    Tend_i=dates_dt.index(TendNew)
> 
> This definitely seems to cleanest way... thank you! One question, how would
> this handle duplicates in the dates_dt list?

index() will return the first found element. If you want Tend_i to be 
the last match you will have to write your own rindex() function. Some 
suggestions are here:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/b25cb46b54cc5ee5/120d04e029e934c5?hl=en&lnk=gst

This one looks good to me:
def rindex(seq, item):
     for pos, el in enumerate(reversed(seq)):
         if item == el:
             return len(seq) - 1 - pos
     else:
         raise ValueError("rindex(list, item): item not in list")

Kent



More information about the Tutor mailing list