代码之家  ›  专栏  ›  技术社区  ›  MarkS

三个强制性的第二个论点

  •  0
  • MarkS  · 技术社区  · 7 年前

    我有一个模仿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

    1 回复  |  直到 7 年前
        1
  •  1
  •   DeepSpace    7 年前

    必须使用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]