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 คือลิสต์ที่มีรายการภายในเป็นลิสต์อีกที
- มันจำลองตารางหรือตาราง: แถวของคอลัมน์
- ลิสต์ภายในแต่ละอันคือหนึ่ง แถว
grid = [[1, 2, 3],
[4, 5, 6]]
print(grid)
Reach one cell
- Use two indexes: first the row, then the column.
grid[row][col]— both count from 0 in Python.
เข้าถึงเซลล์เดียว
- ใช้ สอง index: แรกคือแถว แล้วตามด้วยหลัก
grid[row][col]— ทั้งสองนับจาก 0 ใน Python
grid = [[1, 2, 3], [4, 5, 6]]
print(grid[0][1]) # 2
print(grid[1][2]) # 6
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.
Loop嵌套เข้าเยี่ยมทุกเซลล์
- ลูปภายนอกเดินผ่าน แถว; ลูปภายในเดินผ่าน คอลัมน์
for row in grid:ให้แถวหนึ่ง (list) พร้อมกัน
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value)
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
In the exam: ARRAY[1:rows, 1:cols]
- Pseudocode writes a 2-D array with two ranges, counting from 1.
ในการสอบ: ARRAY[1:แถว, 1:คอลัมน์]
- ปсевโดโค้ดเขียน-array แบบ 2-มิติ ด้วยสองช่วง โดยนับเริ่มตั้งแต่ 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
Common mistakes
- Use two indexes:
grid[row][col]. - The outer loop walks the rows, the inner loop the columns.
ข้อผิดพลาดที่พบบ่อย
- ใช้ตัวชี้สองตำแหน่ง:
grid[row][col] - ลูปภายนอกเดินผ่านแถว ลูปภายในเดินผ่านคอลัมน์
Now you try
- Use a nested loop or two indexes.
- Press Check answer to test your code.
ลองดูเลย
- ใช้ลูปซ้อนหรือใช้ตัวชี้สองตำแหน่ง
- กด Check answer เพื่อทดสอบโค้ดของคุณ
A 2-D array is a grid · 2-D array คือตาราง
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Add up every number in the 2-D list grid with a nested loop. Store the total in total (the answer is 21). · รวม ทุก จำนวนในรายการ 2-D grid ด้วยลูปซ้อน เก็บผลรวมใน total (คำตอบคือ 21).
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a nested loop to print a 3-by-3 square of stars: three lines, each with three * characters. · ใช้ ลูปซ้อน (nested loop) เพื่อพิมพ์ตารางดาวขนาด 3×3: สามบรรทัด แต่ละบรรทัดมี * ตัวอักษรสามตัว
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่