Night 23: A map for your pet
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: a map for your pet
- Your pet's world needs a map: rows and columns, like a chess board.
- You will learn one thing: 2D lists, a list of rows.
Words for tonight
| Word | Meaning |
|---|---|
| grid | rows and columns of boxes |
| row | a line from left to right |
| column | a line from top to bottom |
A list of lists
- Each row is a list. The map is a list of the rows.
world = [
["tree", "grass", "pond"],
["grass", "home", "grass"],
["rock", "grass", "tree"],
]
print(world[1])
print(world[1][1])
world[row][col]: first the row, then the column. Both start at 0.

Change one place
- Use both positions and
=.
grid = [
[".", ".", "."],
[".", ".", "."],
]
grid[1][2] = "P"
for row in grid:
print("".join(row))
"".join(row)glues the items of a row into one text:[".", ".", "P"]becomes..P.
Visit every place
- A loop inside a loop goes through the whole map.
garden = [
["T", "."],
[".", "T"],
]
for row in garden:
for place in row:
print(place)
- Now draw your pet's map!
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Here is your pet's world as a list of rows. Print the place at row 1, column 1, then the place at row 0, column 2. The output is home, then pond.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Put your pet P at row 2, column 0. Then print each row as one line with "".join(row). The last line is P...
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Count the trees T in the garden with a loop inside a loop. Print the count: 3.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Find where H (home) is. Use two loops with range and print its row and column numbers: 1 2.
คลิก Run เพื่อดูผลลัพธ์ที่นี่