嵌套for循环如何工作? [英] How do nested for loops work?
问题描述
这是我编写的代码,可以很好地工作:
This is the code I wrote, works perfectly fine:
box = [1, 2, 3, 4, 5]
for i in box:
for x in box:
print (i,x)
它输出以下内容:
1 1
1 2
1 3
1 4
1 5
2 1
2 2
等
有趣的部分是:我确实得到了想要的东西,但是我真的不理解逻辑.对于我编写的代码,我希望得到以下输出:
The funny part is: I got exactly what I want, however I really don't understand the logic. For the code I wrote, I would expect the following output:
1 1
2 2
3 3
4 4
5 5
为什么?因为根据我的想法,我说了以下内容:
Why? Because by my idea I stated the following:
对于框中的每个值 i
(左列),对于每个值 x
(右列),都应同时打印.
For each value i
(left column) in box and for each value x
(right column) print both.
实际上,我认为该代码应充当:
In fact, the code I believe should act as:
for i,y in zip(box,box):
print(i,y)
我的问题是,为什么函数中的嵌套for循环的行为与我预期的不同?
My question is, why did the nested for-loop in the function behave differently then I expected?
它怎么知道创建 number * number
行?它是如何对数字进行排序的,那里到底发生了什么关系?
How did it know to create number * number
rows?
How did it order the numbers as it has, what relation acutally happened there?
推荐答案
这是逻辑. i in box
, i
将开始为 1
并向前移动,直到成为 5
(列表中的所有元素)).因此,如果在此循环中打印 i
,您会看到 i
首先是 1
,然后 i
是 2
...直到 i
为 5
(框中的最后一个元素).但是,如果您嵌套另一个for循环,则每次 i
与列表中的元素不同时,它都会执行相同的操作(从1开始并向前移动直到5).因此,当 i
为 1
时,在更改为另一个 i
之前,它将开始第二个循环(对于x in box >),因此当 i
为 1
x
时,其更改为 x
== 1
, x
== 2
... x
== 5
.当此嵌套循环完成时, i
将从列表中更改为另一个元素,因此现在 i
将为 2
,并且嵌套循环再次开始,因此 x
== 1
, x
== 2
..., x
== 5
.
It is logic. for i in box
, i
will start being 1
and moving forward until being 5
(all elements from the list). So if you print i
inside this loop, you will see that i
is first 1
, then i
is 2
... until i
is 5
(last element from box).
But if you nest another for loop, it will do the same (start from 1 and moving forward until 5) for each time i
is a different element from the list. So when i
is 1
, before changing to another different i
it will start the second loop (for x in box
), so then when i
is 1
x
will change being x
== 1
, x
== 2
... x
== 5
. When this nested loop finishes, then i
changes to another element from the list, so now i
would be2
, and the nested loop starts again, so x
== 1
, x
== 2
..., x
== 5
.
我想您可以尝试一下
box = [1, 2, 3, 4, 5]
for i in box: #it will go through all elements in the list
print i, "this is the first loop" #for each different 'i' in box
for x in box: #it will go through all elements in the list
print x, "this is the second loop" #you will get all elements from the box
print (i,x) #this is what you get
这篇关于嵌套for循环如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!