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

Kno*_*olt 3 python iteration parameters loops while-loop

从 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
Run Code Online (Sandbox Code Playgroud)

两个开始在 if 语句中做什么?为什么会出现两次?我将后者的开始更改为 int,这将我的列表长度更改为该 int。

我似乎也无法围绕交互部分。在这个例子中,start = 10。所以,当迭代...而 10 < 0 它将继续增长列表,每次增加 step=1 的计数。但是,10 不小于 0。首先怎么跑?

che*_*ner 7

分配应解析为

(start, stop) = (0, start)
Run Code Online (Sandbox Code Playgroud)

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

while循环相当于更直接的for

for i in range(start, stop + 1, step):
    result.append(i)
Run Code Online (Sandbox Code Playgroud)

除了intervallet startstop、 和 之外的step所有类型都不是int.


更好的设计可能是要求使用仅关键字参数,以便函数体中每个参数的使用方式没有歧义:

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

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