第二个论点是三个强制性的 [英] Second argument of three mandatory

查看:79
本文介绍了第二个论点是三个强制性的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模仿range()的函数.我被困在某一点.我需要能够使第一个(x)和第三个(step)参数为可选,但中间一个 参数(y)是强制性的.在下面的代码中,除了两行注释掉的行之外,其他所有内容都有效.

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.

如果仅传递一个参数,我该如何构造函数以将单个传递的参数接受为强制(y)参数?

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?

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

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)

输出:

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

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

推荐答案

您必须使用哨兵值:

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数组)

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]

这篇关于第二个论点是三个强制性的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆