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

washakie washakie at gmail.com
Sun Feb 10 02:35:23 CET 2008


It's not pretty, but this is what seems to work... I'd be happy hear more
about a better approach... I like the idea of using a list, but ran into
troubles with min and max, maybe I don't entirely understand the lambda
function, but when I tried a list, I got an error that min() has no optional
variable 'key' or something along those lines...

Using a technique from: http://www.daniweb.com/code/snippet806.html

def find_key(dic, val):
   """return the key of dictionary dic given the value"""
   return [k for k, v in dic.iteritems() if v == val][0]

dates_dt={}                                                                                                     
for i in range(len(dates_list)):                                                                                   
  
dates_dt[i]=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:]))                            
   TstartNew=sorted(dates_dt.values(),key=lambda d: abs(Tstart - d))[0]                                            
   Tstart_i=find_key(dates_dt,TstartNew)                                                                           
   TendNew=sorted(dates_dt.values(), key=lambda d: abs(Tend -d))[0]                                                
   Tend_i=find_key(dates_dt,TendNew)                                                                               
try:                                                                                                               
   TF=file(os.path.join(TMP_DIR,'dates_file'),'w')                                                                 
   if userInput['animation']=='movie':                                                                                
      for i in range(Tstart_i,Tend_i):                                                                                   
         TF.write("%s\n" % dates_dt[i].strftime("%Y%m%d%H0000"))                                                   
   else:                                                                                                                 
      TF.write("%s\n" % TstartNew.strftime("%Y%m%d%H0000") )                                                                            
   TF.close()	
-- 
View this message in context: http://www.nabble.com/seek-and-slice-a-range-in-a-list-of-dates-tp15389997p15392327.html
Sent from the Python - tutor mailing list archive at Nabble.com.



More information about the Tutor mailing list