Two-dimensional arrays
Python for IGCSE CS Lesson 9 2:03 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A table of marks, a seating plan, a game board — these have rows and columns, and one index is not enough.
一张成绩表、一份座位安排、一个棋盘—— 这些东西有行也有列,一个下标不够用。
A two-dimensional array is a list of lists: each item of the outer list is itself a whole row.
二维数组就是一个列表的列表: 外层列表的每一项,本身就是一整行。
To reach one cell you give two numbers, and the order is fixed.
要取到一个格子,你要给两个数字,而且顺序是固定的。
This one reads as row one, column two, and it holds six.
这个读作"第 1 行、第 2 列",它装的是 6。
Swap the two numbers and you are not being approximate — you are asking for a different cell entirely.
把这两个数字调换一下,那不是"差不多"—— 你要的是完全另一个格子。
On this grid there is no row two, so it errors, and you find out at once.
在这个网格上没有第 2 行,所以它会报错,你立刻就知道了。
On a square grid there would be a row two, and you would get the wrong cell in silence, with a plausible number that is simply not the one you asked for.
但在一个方形的网格上,第 2 行是存在的, 你会悄无声息地拿到错误的那个格子, 得到一个看起来合理、却根本不是你要的数字。
Row first, always.
永远是先行。
To touch every cell you need one loop inside another.
要碰到每一个格子,你需要一个循环套在另一个里面。
The outer loop picks one row at a time.
外层循环每次取出一行。
The inner loop walks along it, cell by cell, and only when it finishes does the outer one move down.
内层循环沿着这一行一格一格地走, 只有等它走完,外层才往下移一行。
Count the passes: the body runs rows times columns times — six here — which is exactly the number of cells.
数一数执行次数: 循环体执行了"行数乘以列数"次——这里是 6 次—— 正好等于格子的数量。
Here is the second task in both notations.
这是第二道题的两种写法。
The declarations look different — the exam writes one pair of brackets with a comma inside, and Python writes two separate pairs — but the walk through the grid is the same nested loop in both.
声明看起来不一样—— 考卷写的是一对方括号,里面用逗号隔开, 而 Python 写的是两对分开的方括号—— 但遍历网格的方式,在两边都是同一个嵌套循环。
Read across, and the pseudocode stops being unfamiliar.
横着读,伪代码就不再陌生了。
Four things to take with you.
带走四点。
One: a two-dimensional array is a list whose items are lists.
第一:二维数组是一个"元素本身也是列表"的列表。
Two: the first index is the row and the second is the column.
第二:第一个下标是行,第二个是列。
Three: an outer loop for rows, and an inner one for columns.
第三:外层循环管行,内层循环管列。
Four: swapping the two indexes gives you a different cell, not a near miss.
第四:把两个下标调换,得到的是另一个格子,不是"差一点"。
Now do the three tasks.
现在去做那三道题。