[Tutor] seek and slice a range in a list of dates
kent37 at tds.net
Sat Feb 9 22:22:14 CET 2008
> I'm using the code below to select the closest dates in a dictionary of
> dates, to selected dates (Tstart, Tend)... Now, I need to get all the dates
> (slice) from the dictionary in between the two dates TstartNew and TendNew.
> Basically, I need to know what the 'index' is for them in the in the
> dictionay dates_dt. How can I get that information out of the lambda
> functions? does python have a 'find' function??
> for i in range(len(dates_list)):
Why do you use a dict here? A list seems more appropriate. Where are
year,month,day,hour,minute,seconds coming from?
> TstartNew=sorted(dates_dt.values(),key=lambda d: abs(Tstart - d))
> TendNew=sorted(dates_dt.values(), key=lambda d: abs(Tend -d))
You could use min() and max() instead of sorting (twice!)
How about something like this (untested):
dates_dt=[ datetime.datetime(year,month,day,hour,minute,seconds) for x
in dates_list ]
adjusted to actually get the dates from somewhere...
key=lambda i: abs(Tstart - dates_dt[i]))
This gives you the index of the date with the min difference.
key=lambda i: abs(Tend - dates_dt[i]))
for the index of the max difference.
The above will work if dates_dt is a dict or a list.
Dates = dates_dt[TstartNew+1:TendNew]
which gives you the dates between and not including the min and max, if
dates_dt is a list. For a dict, use
Dates = [ dates_dt[i] for i in range(TstartNew+1, TendNew) ]
More information about the Tutor