简体   繁体   English

如果在'for'循环中使用'for'函数,它是如何工作的?

[英]How does the 'for' function work if it is used in a 'for' loop?

I'm using the python documentation to begin learning everything, and it introduces the 'for' loop with the 'for' function inside the said 'for' loop. 我正在使用python文档开始学习所有内容,并在所述'for'循环中引入了'for'循环和'for'函数。 I'm doing an awful job of explaining because I'm having such a hard time keeping up with the terminology, so I'll just show you: 我正在做一个很糟糕的解释,因为我很难跟上术语,所以我只会告诉你:

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print n, 'equals', x, '*', n/x
            break
        else:

            print n, 'is a prime number'

I understand the if/else loops, and the break statement. 我理解if / else循环和break语句。 I see that it somehow generates prime numbers between 2 and 10. Other than that, I'm kinda lost with this example. 我看到它以某种方式生成2到10之间的素数。除此之外,我有点迷失这个例子。 The documentation is becoming intolerably verbose, and I am barely able to comprehend very much of it at this point. 文档变得难以忍受,我现在几乎无法理解它。 I was just hoping someone could explain this in slightly simpler terms 我只是希望有人可以用稍微简单的术语解释一下

for n in range(2, 10):

means that n will take on the values of 2 - 10, one at a time, and each time it takes on a new value, run the inner loop. 表示n将取2-10的值,一次取一个值,每次取值为新值时,运行内循环。

The inner loop, 内环,

for x in range(2, n):

means that x will take on the values of 2 - n, one at a time, and execute its innards, the if/else. 表示x将采用2 - n的值,一次一个,并执行其内部,if / else。

So the outer loop starts at 2, so n = 2. The inner loop iterates from 2-n, n=2, so 2-2, so one time. 所以外循环从2开始,所以n = 2.内循环从2-n迭代,n = 2,所以2-2,所以一次。

Then control passes back to the outer loop, n is incremented, and the inner loop is now executed from 2-n, n being 3. So x takes on the values of 2, then 3, and since n is 3, passes back to the outer loop, and so on. 然后控制传递回外部循环,n递增,内部循环现在从2-n执行,n为3.因此x取值2,然后是3,因为n是3,所以传回外循环,等等。

Here is some flow: 这是一些流程:

:start outer, n = 2
:goto inner, x will range from 2 - 2, so x = 2, x hits max for the inner loop
:goto outer, n = 3
:goto inner, x will range from 2 - 3, so x = 2, iterate once, x = 3, x hits max for inner loop
:goto outer, n = 4
:repeat

First things first for is not a function but a construct. 首先第一件事情不是功能,而是一个结构。 Also, if/else is not a loop but a branching construct 另外,if / else不是循环而是分支构造

Consider the labeled code 考虑标记的代码

for n in range(2, 10): # this is the outer loop
    for x in range(2, n): # this is the inner loop 
                          #(this is where the code is checking whether n is prime)
        if n % x == 0: #checking is x divides n
            print n, 'equals', x, '*', n/x
            break
        else:

            print n, 'is a prime number'

next, the outer for loop iterates from 2 to 10. Each iteration of the loop has another inner for loop. 接下来, 外部 for循环从2到10迭代。循环的每次迭代都有另一个内部 for循环。 This inner loop iterates from 2 to that number and checks for divisibility to check of the variable n (outer loop) is a prime number or not. 这个内部循环从2迭代到该数字,并检查可分性以检查变量n(外循环)是否为素数。

For example: 例如:

For the first iteration
n=2
x=nothing

,then ,然后

n=3
x=2

and

n=4
x=2,3

and so on. 等等。

just to add in python, unlike other popular languages the for loop does not increment the variable. 只是为了添加python,与其他流行语言不同,for循环不会增加变量。 Instead it just selects a value at a time from a list/array of values that you specify (for ex: range(2,10) in this case is an array [2 3 4 5 6 7 8 9] 相反,它只是从您指定的列表/数组中一次选择一个值(例如:范围(2,10)在这种情况下是一个数组[2 3 4 5 6 7 8 9]

I'm going to definitely agree with @Josh and @gddc's answer here, but there's a bit more that needs to be explained to understand the for loop construct, and what its power really is. 我在这里肯定会同意@Josh和@gddc的答案,但还需要解释一下才能理解for循环结构,以及它的功能究竟是什么。 But to get that, I'd have to talk just a little bit on what an iterable object is. 但为了实现这一点,我不得不谈论可迭代对象是什么。


Python's for loops don't work the same way they would in another language,like Java for instance. Python的for循环与其他语言(例如Java)的工作方式不同。 The for loops here require something they can iterate over. 这里的for循环需要他们可以迭代的东西。 This means three datatypes (in general): lists, tuples, and dictionaries. 这意味着三种数据类型(通常):列表,元组和字典。 All three of these have values that can be iterated over, and as such, a for loop will work fine with them. 所有这三个都具有可以迭代的值,因此, for循环可以很好地与它们一起工作。

The range(a, b, s) function will generate a list of values in the range [a, b), optionally with a skip value s. range(a, b, s)函数将生成范围[a,b)中的值列表,可选地具有跳跃值s。 Since a list is iterable, we can use it with the for statement. 由于列表是可迭代的,我们可以将它与for语句一起使用。

When you nest for statements, you are performing a nested loop . 当你 for语句,则执行的是嵌套循环 The furthest for statement in will operate the most often. 声明最远for将是最常见的。 You can compare a nested loop to an analog time piece - the second hand is the innermost for , the minute hand is a level above that, and the hour hand is a level above that. 您可以将嵌套循环与模拟时间片进行比较 - 秒针是最里面for ,分针是高于该值的水平,而时针是高于该水平的水平。

Now, onto this example. 现在,进入这个例子。 In the outside for loop, we bind every value we get from the iterable list to a variable - in this case, n . 在外部for循环中,我们将从iterable列表中获得的每个值绑定到一个变量 - 在本例中为n When we start the loop, n == 2 . 当我们开始循环时, n == 2 We come to the inner for loop, and notice that we bind the variable x to the list [2, 2) , which would be empty - having the same start and end point in a range() doesn't return anything. 我们来到内部for循环,注意我们将变量x绑定到列表[2, 2) ,这将是空的 - 在range()中具有相同的起点和终点不返回任何内容。 So the first time through, we would skip the inner loop. 所以第一次,我们将跳过内循环。

Once we're done with the inner level loop, we come back and repeat the outer loop. 一旦我们完成内部循环,我们回来重复外循环。 So now, n == 3 . 所以现在, n == 3 We come to the inner loop, and bind x to the first value in the iterable range [2, 3) , which would be 2 . 我们来到内部循环,并将x绑定到可迭代范围[2, 3)的第一个值,即2 We then perform the inner operations, as expected of the if statement. 然后我们按照if语句的预期执行内部操作。

When we finally get to a point when n == 9 (maximum value; remember, n can never equal 10 in this example due to the range limits), x will be bound to the first value of the iterable range [2, 9) . 当我们最终达到n == 9 (最大值;记住,由于范围限制, n在本例中n不能等于10)时, x将被绑定到可迭代范围的第一个值[2, 9) 2,9 [2, 9) So x will start at 2, then move to 3, and so forth. 所以x将从2开始,然后移到3,依此类推。

If you want to learn more on how for loops work, then I recommend looking into list comprehensions , and even referencing Dive into Python's section on lists . 如果您想了解更多关于如何for循环工作,那么我建议寻找到列表理解 ,甚至引用潜入Python的名单上的部分

When you nest for loops the inner loop gets repeated for every round of the outer loop. 嵌套for循环时,内循环会在外循环的每一轮中重复出现。 So, for your example, it starts like this: 所以,对于你的例子,它是这样开始的:

for x in range(2, 2):

Then proceeds to 然后继续前进

for x in range(2, 3):

and so on. 等等。 Each inner loop grows one step longer for each step of the outer loop. 对于外环的每个步骤,每个内环增长一步。 Because the break is within the inner loop, the outer loop will run in its entirety regardless of how many times the inner loop break s. 因为break在内部循环内,所以无论内部循环break多少次,外部循环都将完整地运行。

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

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