Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将时间间隔划分为不同长度的部分?_Python_Python 3.x_Math_Numerical Integration - Fatal编程技术网

Python 如何将时间间隔划分为不同长度的部分?

Python 如何将时间间隔划分为不同长度的部分?,python,python-3.x,math,numerical-integration,Python,Python 3.x,Math,Numerical Integration,我有一个从0到t的时间间隔。 我想按照以下方式将该间隔划分为2.25、2.25和1.5周期内的累积序列: 输入: start = 0 stop = 19 输出: sequence = [0, 2.25, 4.5, 6, 8.25, 10.5, 12, 14.25, 16.5, 18, 19] 如何在Python中实现这一点 其思想是将一个时间段划分为6小时的周期,每个周期由三个连续操作组成,分别持续2.25小时、2.25小时和1.5小时。或者,有没有替代使用“里程碑”的方法呢?您可以使用

我有一个从0到
t
的时间间隔。 我想按照以下方式将该间隔划分为2.25、2.25和1.5周期内的累积序列:

输入:

start = 0
stop = 19
输出:

sequence = [0, 2.25, 4.5, 6, 8.25, 10.5, 12, 14.25, 16.5, 18, 19] 
如何在Python中实现这一点



其思想是将一个时间段划分为6小时的周期,每个周期由三个连续操作组成,分别持续2.25小时、2.25小时和1.5小时。或者,有没有替代使用“里程碑”的方法呢?

您可以使用生成器:

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

您还可以使用以避免外部循环:

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

不是最干净的。但它是有效的

>>> 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]
>>开始=0
>>>停止=19
>>>步骤=[2.25,2.25,1.5]
>>>L=[开始]
>>>当L[-1]>>L[-1]=停止时
>>>L
[0, 2.25, 4.5, 6.0, 8.25, 10.5, 12.0, 14.25, 16.5, 18.0, 19]
将步骤值保存在列表中。只需迭代并不断循环添加它们,直到达到上限

>>> 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]