必须使用sentinel值:
def float_range(value, end=None, step=1.0):
if end is None:
start, end = 0.0, value
else:
start = value
if start < end:
while start < end:
yield start
start += step
else:
while start > end:
yield start
start += step
for n in float_range(0.5, 2.5, 0.5):
print(n)
# 0.5
# 1.0
# 1.5
# 2.0
print(list(float_range(3.5, 0, -1)))
# [3.5, 2.5, 1.5, 0.5]
for n in float_range(0.0, 3.0):
print(n)
# 0.0
# 1.0
# 2.0
for n in float_range(3.0):
print(n)
# 0.0
# 1.0
# 2.0
顺便说一句,
numpy
工具
arange
这本质上是你想要重新发明的,但它不是一个生成器(它返回一个numpy数组)
import numpy
print(numpy.arange(0, 3, 0.5))
# [0. 0.5 1. 1.5 2. 2.5]