Nested loops & 2-D lists · 중첩 루프 & 2D 리스트
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-D 리스트는 Item 자체가 리스트인 리스트입니다.
- 격자 또는 표를 모델링합니다: 행의 열들.
- 두 개의 인덱스로 특정 셀에 도달합니다:
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].
캐미지아 가위코드에서
- A 2-D 목록은 시험의 2-D 배열이며,
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.
이제 직접 해보기
- 각 작업에서 중첩된 루프를 사용하십시오.
- Answer 확인 버튼을 눌러 코드를 테스트하세요.
A 2-D list is a grid · 2D 리스트는 격자입니다
A 2-D list is rows of columns; reach a cell with grid[row][col]. · 2D 리스트는 열의 행렬이며, 특정 셀에 접근하려면 **grid[row][col]**을 사용합니다.
Use a nested loop to print a 3-by-3 square of stars: three lines, each with three * characters. · 중첩된 루프를 사용하여 별 3x3 사각형을 출력합니다: 총 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. · 출력을 보려면 '실행'을 클릭하세요.