问题
I have a function that mimics range(). I am stuck at one point. I need to be able to make the first (x) and third (step) arguments optional, but the middle argument (y) mandatory. In the code below, everything works except the two commented out lines.
If I am only passing in one argument, how do I construct the function to accept the single passed in argument as the mandatory (y) argument?
I cannot do this: def float_range(x=0, y, step=1.0):
Non-default parameter cannot follow a default parameter.
def float_range(x, y, step=1.0):
if x < y:
while x < y:
yield x
x += step
else:
while x > y:
yield x
x += step
for n in float_range(0.5, 2.5, 0.5):
print(n)
print(list(float_range(3.5, 0, -1)))
for n in float_range(0.0, 3.0):
print(n)
# for n in float_range(3.0):
# print(n)
Output:
0.5
1.0
1.5
2.0
[3.5, 2.5, 1.5, 0.5]
0.0
1.0
2.0
回答1:
You have to use sentinel values:
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
By the way, numpy
implements arange
which is essentially what you are trying to reinvent, but it isn't a generator (it returns a numpy array)
import numpy
print(numpy.arange(0, 3, 0.5))
# [0. 0.5 1. 1.5 2. 2.5]
来源:https://stackoverflow.com/questions/51250476/second-argument-of-three-mandatory