繁体   English   中英

我怎样才能使这个自定义范围 function 与负步一起工作?

[英]How can I make this custom range function work with negative steps?

这是我到目前为止所拥有的。 它与其他 3 个 arguments 一起正常工作,但是一旦我将步骤更改为负数,它就不会返回预期的 output。我在最后添加了内置范围 function 作为参考。

def myRange(start, stop = None, step = None):
    if(step == None and stop== None ):
        stop = start
        start = 0
        step = 1
    elif(step == None):
        step = 1
    res = []
    if (step < 0):
        while stop < start:
            res.append(start)
            start += step
   

    else:
        while start < stop:
            res.append(start)
            start += step
        return res

def main():
    print(myRange(5, 20))
    print(myRange(5, 100, 5))
    print(myRange(20, 10, -1))
    print(list(range(20, 10, -1)))
    print(myRange(100, 500, 50))
if __name__ == '__main__':
    main()

你犯了一个小错误,你应该取消return res的缩进。
像这样

else:
     while start < stop:
         res.append(start)
         start += step
return res

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM