Skip to content

Nested loops

Python for A-Level CS Lesson 1 2:07 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
One loop inside another sounds simple, and one sentence about it gets misread every year: for every single pass of the outer loop, the inner loop runs all three of its turns. 一个循环套在另一个里面听起来很简单, 而关于它有一句话每年都被读错: 外层循环每走一步,内层循环都会把它自己的三轮全部跑完。
Watch the two counters. 看这两个计数器。
The outer one moves once; the inner one moves three times. 外层动一次,内层动三次。
Three and nine — a ratio, not a sequence. 3 和 9——这是一个比例,不是一个先后顺序。
That ratio is exactly why a nested loop touches every cell of a grid. 正是这个比例,让嵌套循环能碰到网格里的每一个格子。
The structure that ratio is built for is the two-dimensional list — a list whose every item is itself a whole row. 这个比例是为二维列表准备的—— 一个列表,它的每一项本身就是一整行。
Reaching one cell therefore takes two indexes, in a fixed order: row first, then column. 因此,取到某一个格子需要两个下标,顺序固定:先行,后列。
The first bracket picks the row out of the outer list; the second picks the value out of that row. 第一个方括号从外层列表里取出那一行, 第二个方括号再从那一行里取出那个值。
There are two ways to write the walk, and both are worth having. 写这个遍历有两种方式,两种都值得掌握。
Looping over the values themselves is shorter and reads better when all you need are the numbers. 直接遍历值本身更短, 当你只需要那些数字时,它读起来也更顺。
Looping over indexes is longer, but it is what you need when you must know WHERE a value is — to change it, or to report its position. 按下标遍历更长, 但当你必须知道某个值在"哪里"时就得用它—— 比如要修改它,或者要报告它的位置。
And the index version is the one the exam writes, because pseudocode has no way to walk values directly. 而按下标的那种,正是考卷上的写法, 因为伪代码没有直接遍历值的办法。
The third task counts the zeros in a grid, and it is the accumulator you already know, sitting two levels deep. 第三道题是数网格里有多少个 0, 它就是你已经熟悉的那个累加器,只是嵌在两层循环里面。
The one thing to get right is where the counter starts: outside BOTH loops, before either begins. 唯一要做对的,是计数器在哪里初始化: 在两层循环之外,在它们都还没开始之前。
Put it inside the outer loop and it resets on every row; inside the inner one and it never exceeds one. 放在外层循环里面,它每一行都会被清零; 放在内层里面,它永远不会超过 1。
Four things to take with you. 带走四点。
One: the inner loop finishes fully on every outer pass. 第一:外层每走一步,内层都完整跑完一遍。
Two: a 2-D list is a list whose items are lists. 第二:二维列表是一个"元素本身也是列表"的列表。
Three: outer for rows, inner for columns, and the row index first. 第三:外层管行,内层管列,行下标写在前面。
Four: a counter or a total starts outside both loops. 第四:计数器或累加器在两层循环之外初始化。
Now do the three tasks. 现在去做那三道题。

Log in or create account

IGCSE, A-Level & AP