Nested loops & 2-D lists · 嵌套循环与二维列表
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
A loop inside a loop
- You can put one loop inside another loop.
- For every pass of the outer loop, the inner loop runs fully.
- So an outer of 2 and an inner of 3 runs the body 2 × 3 = 6 times.
中文
循环里套循环
- 你可以把一个循环放进另一个循环里面。
- 外层循环每跑一轮,内层循环就完整地跑一遍。
- 所以外层 2 次、内层 3 次,循环体会运行 2 × 3 = 6 次。
for row in range(2):
for col in range(3):
print(row, col)
English
A list of lists
- A 2-D list is a list whose items are themselves lists.
- It models a grid or table: rows of columns.
- Reach one cell with two indexes:
grid[row][col].
中文
列表里的列表
- 二维列表(2-D list)是一个其元素本身也是列表的列表。
- 它用来表示网格或表格:由若干行的若干列组成。
- 用两个索引访问某个单元格:
grid[row][col]。
grid = [[1, 2], [3, 4]]
print(grid[0][1])
print(grid[1][0])
English
Loop over a grid
- Use a nested loop to visit every cell.
- The outer loop walks the rows; the inner loop walks the columns.
for row in grid:gives one row (a list) at a time.
中文
遍历网格
- 用嵌套循环访问每个单元格。
- 外层循环走行;内层循环走列。
for row in grid:每次取出一行(一个列表)。
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value)
English
In Cambridge pseudocode
- A 2-D list is the exam's 2-D array, written
ARRAY[1:rows, 1:cols].
中文
用剑桥伪代码表示
- 二维列表就是考试里的二维数组(2-D array),写作
ARRAY[1:rows, 1:cols]。
DECLARE grid : ARRAY[1:2, 1:3] OF INTEGER
FOR r ← 1 TO 2
FOR c ← 1 TO 3
OUTPUT grid[r, c]
NEXT c
NEXT r
English
Common mistakes
- The inner loop finishes all its turns for each single turn of the outer loop.
- Index a grid row first, then column:
grid[row][col].
中文
常见错误
- 外层每转一次,内层要跑完它的所有轮次。
- 网格先按行再按列索引:
grid[row][col]。
English
Now you try
- Use a nested loop in each task.
- Press Check answer to test your code.
中文
现在轮到你
- 每个任务都要用嵌套循环。
- 按检查答案来测试你的代码。
Explore · 探索
A 2-D list is a grid · 二维列表就是网格
A 2-D list is rows of columns; reach a cell with grid[row][col]. · 二维列表是若干行、每行若干列;用 grid[row][col] 取一个格子。
Use a nested loop to print a 3-by-3 square of stars: three lines, each with three * characters. · 用嵌套循环打印一个 3×3 的星号方块:三行,每行三个 *。
Click Run to see the output here. · 点击“运行”查看此处输出。
Add up every number in the 2-D list grid with a nested loop. Store the total in total (the answer is 21). · 用嵌套循环把二维列表 grid 中的每个数字加起来。把总和存进 total(答案是 21)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Count how many cells in the 2-D list grid are equal to 0. Store the count in count (the answer is 3). · 统计二维列表 grid 中有多少个单元格等于 0。把数量存进 count(答案是 3)。
Click Run to see the output here. · 点击“运行”查看此处输出。