首页 > 解决方案 > 三个强制的第二个参数

问题描述

我有一个模仿 range() 的函数。我被困在某一时刻。我需要能够使第一个 (x) 和第三个 (step) 参数可选,但中间参数 (y) 是必需的。在下面的代码中,除了两条注释掉的行之外,一切正常。

如果我只传入一个参数,我如何构造函数以接受单个传入的参数作为强制 (y) 参数?

我不能这样做: def float_range(x=0, y, step=1.0):

非默认参数不能跟随默认参数。

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)

输出:

0.5 1.0 1.5 2.0 [3.5, 2.5, 1.5, 0.5] 0.0 1.0 2.0

标签: python-3.xfunctionpython-3.6

解决方案


您必须使用标记值:

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

顺便说一句,numpyimplementsarange本质上是您要重新发明的东西,但它不是生成器(它返回一个 numpy 数组)

import numpy

print(numpy.arange(0, 3, 0.5))
# [0.  0.5 1.  1.5 2.  2.5]

推荐阅读