【问题标题】:Second argument of three mandatory三个强制的第二个参数
【发布时间】:2018-07-09 16:51:16
【问题描述】:

我有一个模仿 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.x function python-3.6


【解决方案1】:

你必须使用标记值:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 2021-10-19
    • 2013-09-11
    • 2012-06-03
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多