Nested loops & 2-D lists · ネストループと 2次元リスト
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)
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次元リストとは、その要素自体がリストであるリストです。
- グリッドや表をモデル化します:列の行。
- 二つのインデックスで特定のセルにアクセスします:
grid[row][col]。
grid = [[1, 2], [3, 4]]
print(grid[0][1])
print(grid[1][0])
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)
In Cambridge pseudocode
- A 2-D list is the exam's 2-D array, written
ARRAY[1:rows, 1:cols].
Cambridge擬似コードにおける表現
- 2次元リストは試験の2次元配列であり、
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
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]。
Now you try
- Use a nested loop in each task.
- Press Check answer to test your code.
あなたも試してみよう
- 各タスクでネストループを使用します。
- 回答を確認 を押してコードを試してください。
A 2-D list is a grid · 2次元リストとはグリッドのことです
A 2-D list is rows of columns; reach a cell with grid[row][col]. · 2次元リストは列の行であり、grid[row][col] でセルにアクセスします。
Use a nested loop to print a 3-by-3 square of stars: three lines, each with three * characters. · ネストされたループを使って、3行×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). · 2次元リスト 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). · 2次元リスト grid において 0 と等しいセルがいくつあるか数える。その数を count に格納する(答えは3)。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。