为什么Python range()在for循环中运行两次 [英] Why Python range() in for loop running twice

查看:791
本文介绍了为什么Python range()在for循环中运行两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有for循环的python range()但是情况是2个循环,期望外循环运行一次,然后循环运行完全,然后外循环运行它的第二个...问题:为什么外循环运行两次之前inter循环有机会运行吗?



我尝试过:



I am using python range() with for loop but situation is 2 loops, expect the outer loop run once, then inter loop runs completely, then outer loop runs its 2nd... question: why the outer loop run twice before the inter loop get a chance to run?

What I have tried:

def sort(a_list):
    for i in range(1,len(a_list)):
        print("i=",i)
        for j in range(i-1,0,-1):
            print("j=",j)






Test: L=[9,6,1,3]





sort(L)



结果:





sort(L)

Result:

i= 1
i= 2   # here, the outer lopp ran twice then inter loop began.
j= 1
i= 3
j= 2
j= 1

推荐答案

如果你想要确切了解这段代码是如何工作的,请使用调试器。它是调试你和你对代码的理解。



看来 i 循环执行两次因为它不行。内部 j 循环执行,但 range i - 1返回一个值数组为0,上限为0是不包含的。



的第一次迭代中我,这将是范围(1 - 1,0,-1),它将不返回 j 循环。



这是预期的行为。
If you want to find out exactly how this code work, use the debugger. It's there to debug YOU and your understanding of the code.

It appears the i loop executes twice in a row because it doesn't. The inner j loop executes but range returns an array of values from i - 1 to 0, with the upper limit of 0 being non-inclusive.

On the first iteration of i, that would be range(1 - 1, 0, -1), which will return no values for the j loop.

This is the expected behavior.


查看内循环的值。第一次运行变量i保持值1.因此循环将不会运行,因为i - 1为零,并且循环被定义为从零值运行到零。
Look at the values of your inner loop. The first time it runs the variable i holds the value 1. So the loop will not run since i - 1 is zero, and the loop is defined to run from values zero to zero.


引用:

为什么外循环在inter循环运行之前运行两次?

why the outer loop run twice before the inter loop get a chance to run?



有关解释的详细信息,请阅读文档:

4。内置类型 - Python 3.7.0文档 [ ^ ]


这篇关于为什么Python range()在for循环中运行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆