putting date strings in order

Peter Otten __peter__ at web.de
Fri May 15 08:01:48 CEST 2009


noydb wrote:

> On May 14, 4:13 pm, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
>> Peter Otten wrote:
>> > Hm, if ordered_raster_list is guaranteed to contain one string item for
>> > every month the above can be simplified to
>>
>> > months = [
>> > 'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
>> > 'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
>> > 'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']
>>
>> > start = 2
>> > ordered_raster_list = months[start-1:] + months[:start-1]
>>
>> Or even:
>> >
>> multi_months = [
>> 'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
>> 'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
>> 'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec'] * 2
>> start = 2
>> ordered_raster_list = multi_months[start - 1: start + 11]
>>
>> --Scott David Daniels
>> Scott.Dani... at Acm.Org
> 
> Peter and Scott --
> 
> ordered_raster_list is guaranteed to have one string item for all 12
> months -- it is just NOT guaranteed to have those in chronological
> order, which is what is required, whether the data starts in january
> (thus ending in dec of same year) or august (thus ending in jul of the
> following year) or whenever.  The initial order of the list is
> dictated by when the raster (precip_<month>) was added to it's
> container.  One would hope the rasters would be added in order, but I
> cannot count on that and shouldn't.

Then you can indeed build the list directly instead of reading it out of 
ListRasters(...) and then sorting it. 

You will get wrong results when there are missing or duplicate months anyway 
unless you work the start month into the lookup dictionary

ordered_months = months[start-1:] + months[:start-1]
month_dict = dict(zip(ordered_months, range(12)))
ordered_raster_list.sort(key=month_dict.get)

or use the modulo key.

Peter




More information about the Python-list mailing list