本文介绍了如何将时间间隔分成不同长度的部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的时间间隔是从0到t.我想通过以下方式将这个间隔分为一个周期为2.25、2.25和1.5的累积序列:

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:

输入:

start = 0
stop = 19

输出:

sequence = [0, 2.25, 4.5, 6, 8.25, 10.5, 12, 14.25, 16.5, 18, 19] 

如何在Python中做到这一点?

How can I do this in Python?

这个想法是将一个时间段划分为6小时的循环,每个循环包括三个连续的操作,分别持续2.25 h,2.25 h和1.5 h.还是为此目的使用里程碑"的替代方法?

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?

推荐答案

您可以使用生成器:

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]


您还可以使用 itertools.cycle 来避免外部循环:


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

这篇关于如何将时间间隔分成不同长度的部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:43