Reputation: 2712
The Python range()
built-in function is limited to integers.
I need a more generic function of similar signature range(start, stop, step)
, where start
, stop
and step
may be of any types given that:
step
to start
is defined,start
and the result mentioned above can be compared with stop
.The function may be used (for example) to obtain a sequence of days of the year:
range(datetime.datetime(2015, 1, 1),
datetime.datetime(2016, 1, 1),
datetime.timedelta(1))
I know I can easily write such function by myself. However, I am looking for efficient existing solutions in some popular package (like numpy or scipy), working with both Python 2 and Python 3.
I have already tried to combine itertools.takewhile
with itertools.count
, however the latter seems to be limited to numbers.
Upvotes: 0
Views: 61
Reputation: 7006
You can do this with a simple generator. The following example works with floats, integers and datetime.
With datetime you just need to clearly specify the exact date (1 Jan 2016) not just 2016 and clearly specify the time delta (timedelta(days=1) not timedelta(1))
import datetime
def range2(start,stop,step):
value = start
while value <= stop:
yield value
value += step
for date in range2(datetime.datetime(2015,1,1),datetime.datetime(2016,1,1),datetime.timedelta(days=1)):
print(date)
As for off-the-shelf solutions there is arange
in numpy but I haven't tested that with datetime.
>>> from numpy import arange
>>> arange(0.5, 5, 1.5)
array([0.5, 2.0, 3.5])
Upvotes: 1