Time travel - how to simplify?

Ben Finney ben+python at benfinney.id.au
Tue Nov 14 14:43:25 EST 2017


Andrew Z <formisc at gmail.com> writes:

> Now i want to get certain number of months. Say, i need  3 months duration
> starting from any month in dict.
>
> so if i start @ 7th:
> my_choice =7
>  for mnth, value in fut_suffix:
>     if my_choice >= mnth
>        # life is great
> but if :
> my_choice = 12 then my "time travel" becomes pain in the neck..

The ‘itertools’ library in the Python standard library
<URL:https://docs.python.org/3/library/itertools.html> has what you
need:

    import itertools

    month_values = sorted(list(fut_suffix.keys()))
    month_cycle = itertools.cycle(month_values)

    month_choice = 7
    three_months_starting_at_choice = []
    while len(three_months_starting_at_choice) < 3:
        this_month = next(month_cycle)
        if this_month >= month_choice:
            three_months_starting_at_choice.append(this_month)

-- 
 \      “God forbid that any book should be banned. The practice is as |
  `\                  indefensible as infanticide.” —Dame Rebecca West |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list