python - 在Python Hetland的书中示例中理解区间函数及其参数

标签 python loops while-loop parameters iteration

从 Hetland 的 Python 书中获取了这个示例函数。

def interval(start, stop=None, step=1):
    if stop is None:
        start, stop=0, start
    result = []

    i = start
    while i < stop:
        result.append(i)
        i += step
    return result

if 语句中两者都开始执行什么操作?为什么会出现两次?我将后者的 start 更改为 int ,这将我的列表的长度更改为该 int 。

我似乎也无法理解交互部分。在示例中,start = 10。因此,当迭代时...当 10 < 0 时,它将继续增长列表,每次增加计数 step=1。但是,10 并不小于 0。首先是如何运行的?

最佳答案

分配应解析为

(start, stop) = (0, start)

也就是说,interval(10) 相当于 interval(0, 10)。尽管第一个参数的名称start,但如果只提供一个参数,它实际上是stop值。

while 循环相当于更直接的 for 循环

for i in range(start, stop + 1, step):
    result.append(i)

除了 interval 之外,让 startstopstep 都具有 int< 以外的类型.

<小时/>

更好的设计可能是要求使用仅关键字参数,这样函数体中每个参数的使用方式就不会出现歧义:

def interval(*, start=0, stop, step=1):
    result = []
    while start < stop:
        result.append(start)
        start += step
    return result

现在您可以调用interval(stop=10)interval(start=3, stop=10);无论哪种方式,参数 start 实际上都是两种情况下的起始值。不过,这是一种权衡,因为您不能再为最常见的用例编写 interval(10)

关于python - 在Python Hetland的书中示例中理解区间函数及其参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131021/

相关文章:

python - 检索人员的最新对象

php - 没有重复帖子的嵌套循环wordpress

python - While循环语法错误

Java while 函数每1秒才执行一次

c++ - 重新启动后,线程无法在while循环中再次运行

python - 警告 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

python - 将整个 JSON 文件上传到 Firebase

python - 来自 python 字典的多个赋值

Python 将列表拆分为给定开始/结束关键字的子列表

java - 如何在循环中将当前迭代的值添加到上一个迭代的值