python-3.x - 三个强制的第二个参数
问题描述
我有一个模仿 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
解决方案
您必须使用标记值:
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
implementsarange
本质上是您要重新发明的东西,但它不是生成器(它返回一个 numpy 数组)
import numpy
print(numpy.arange(0, 3, 0.5))
# [0. 0.5 1. 1.5 2. 2.5]
推荐阅读
- android - 使用改造从 android 应用程序使用 django restful api 将图像上传到服务器
- recursion - 递归的空间复杂度
- node.js - MongoDb $merge 没有向集合添加/更新数据
- javascript - 使用 as 进行转换时,React 中的 Tsx 编译错误
- dart - 为什么 operator ==(Object other) 接受可为空的参数?
- sql - 循环遍历记录集并根据条件将记录写入特定行
- vue.js - Vue.js 计算/移动属性从数据到计算
- encryption - 为什么要对安全文档传输进行两步加密?
- python - Python ROS 与 Anaconda
- node.js - Puppeteer 无法在无头模式下抓取数据,但能够在非无头模式下抓取。怎么修?