问题
I have a time interval from 0 to t
.
I want to divide this interval into a cumulative sequence in a cycle of 2.25, 2.25 and 1.5, in the following manner:
input:
start = 0
stop = 19
output:
sequence = [0, 2.25, 4.5, 6, 8.25, 10.5, 12, 14.25, 16.5, 18, 19]
How can I do this in Python?
The idea is to divide a time period into cycles of 6 hours, each cycle consisting of three sequential operations that last 2.25 h, 2.25 h and 1.5 h respectively. Or is there an alternative to using 'milestones' for this purpose?
回答1:
You could use a generator:
def interval(start, stop):
cur = start
yield cur # return the start value
while cur < stop:
for increment in (2.25, 2.25, 1.5):
cur += increment
if cur >= stop: # stop as soon as the value is above the stop (or equal)
break
yield cur
yield stop # also return the stop value
It works for the start and stop you proposed:
>>> list(interval(0, 19))
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]
You could also use itertools.cycle to avoid the outer loop:
import itertools
def interval(start, stop):
cur = start
yield start
for increment in itertools.cycle((2.25, 2.25, 1.5)):
cur += increment
if cur >= stop:
break
yield cur
yield stop
回答2:
Not the cleanest. But it works.
>>> start = 0
>>> stop = 19
>>> step = [2.25, 2.25, 1.5]
>>> L = [start]
>>> while L[-1] <= stop:
... L.append(L[-1] + step[i % 3])
... i += 1
...
>>> L[-1] = stop
>>> L
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]
Keep your step values in a list. Just iterate over and keep adding them in rotation till you hit the cap.
来源:https://stackoverflow.com/questions/44419487/how-to-divide-time-interval-into-parts-of-varying-length