2-D arrays · 二维数组
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 grid of rows and columns
- A 2-D array is a list whose items are themselves lists.
- It models a grid or table: rows of columns.
- Each inner list is one row.
中文
由行和列组成的网格
- 二维数组(2-D array)是一个其元素本身也是列表的列表。
- 它用来表示网格或表格:由若干行的若干列组成。
- 每个内层列表就是一行(row)。
grid = [[1, 2, 3],
[4, 5, 6]]
print(grid)
English
Reach one cell
- Use two indexes: first the row, then the column.
grid[row][col]— both count from 0 in Python.
中文
取出一个格子
- 用两个索引:先行,后列。
grid[row][col]—— 在 Python 里两者都从 0 开始数。
grid = [[1, 2, 3], [4, 5, 6]]
print(grid[0][1]) # 2
print(grid[1][2]) # 6
English
A nested loop visits 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
Add up a grid
- Keep a running
totaland add every cell with a nested loop.
中文
把网格加起来
- 用一个不断累积的
total,通过嵌套循环把每个格子加上去。
grid = [[1, 2, 3], [4, 5, 6]]
total = 0
for row in grid:
for value in row:
total = total + value
print(total) # 21
English
In the exam: ARRAY[1:rows, 1:cols]
- Pseudocode writes a 2-D array with two ranges, counting from 1.
中文
在考试里:ARRAY[1:rows, 1:cols]
- 伪代码用两个范围写二维数组,从 1 开始数。
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
- Use two indexes:
grid[row][col]. - The outer loop walks the rows, the inner loop the columns.
中文
常见错误
- 用两个索引:
grid[row][col]。 - 外层循环走行,内层循环走列。
English
Now you try
- Use a nested loop or two indexes.
- Press Check answer to test your code.
中文
现在轮到你
- 用嵌套循环或两个索引。
- 按检查答案来测试你的代码。
Explore · 探索
A 2-D array is a grid · 二维数组就是网格
Rows of columns; reach a cell with grid[row][col]. · 若干行、每行若干列;用 grid[row][col] 取一个格子。
From the grid, store the value in row 1, column 2 in a variable x (the answer is 6). · 从网格中,把第 1 行、第 2 列的值存进变量 x(答案是 6)。
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. · 点击“运行”查看此处输出。
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. · 点击“运行”查看此处输出。