# Dashuang Python introductory tutorial 6-4 container advanced nested 2D list

Teaching plan of open course for introduction to Dashuang Python Click to view the tutorial directory

### 1 double layer cycle

Double layer loop, or nested loop,
Set a cycle in a cycle.

Before introducing nested containers, introduce nested loops.

What's the use.

For example, how to output 9x9 multiplication table.

1x1= 1
1x2= 2  2x2= 4
1x3= 3  2x3= 6  3x3= 9
1x4= 4  2x4= 8  3x4=12  4x4=16
1x5= 5  2x5=10  3x5=15  4x5=20  5x5=25
1x6= 6  2x6=12  3x6=18  4x6=24  5x6=30  6x6=36
1x7= 7  2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49
1x8= 8  2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64
1x9= 9  2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81

Its implementation code is as follows

for i in range(1, 10):
for j in range(1, 10):
if j <= i:
print("{}x{}={:>2} ".format(j, i, i*j), end=" ")

print()

Now let's analyze the code,
What do i and j represent in the two-layer loop.

i stands for 1-9 in blue
j stands for green 1-9

Two layer cycle:
The second layer of loop is used to output specific columns on a row,
That is, after the execution of the second layer loop, a line is output.

The first layer of loop is used to output multiple lines,
Specifically, the second layer loop is executed multiple times to output multiple lines.

To understand i and j, it is best to understand them from the perspective of rows and columns.

### 2. Recognize nested lists

#### Preliminary introduction

The nested list inside the list is often called a two-dimensional list.
For example, this is a 3x3(3 rows and 3 columns) binary list.

[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]

So what's the point of such a list,
Two dimensional lists are often used to represent two-dimensional lattice games.
For example, 3x3 above can be used to represent tic tac toe chess.

#### Example a tic tac toe chess

For example, the tic tac toe chess below.

How to use a two-dimensional list
In fact, there is a great degree of flexibility at this time.
That is, we can choose which chess piece is represented by which symbol,
Of course, different representations,
It may make the difficulty of solving relevant problems different.

Here are two representations (not unique, but freely defined).

1. With numbers
The grid without chess pieces is represented by 0
The grid with X pieces is represented by 1
The grid with O pieces is represented by 2
Then the above tic tac toe chess is represented by a list as follows
board = [
[1, 1, 1],
[2, 1, 0],
[2, 0, 2],
]
1. Use letters
Spaces without chessmen are represented by a space ""
The grid with X pieces is represented by "X"
The grid with O pieces is represented by "O"
Then the above tic tac toe chess is represented by a list as follows
board = [
["X", "X", "X"],
["O", "X", " "],
["O", " ", "O"],
]

#### Example 2 Tetris

I've done one before Tetris tutorial
But the whole tutorial is complicated at this stage.
Here we only take the two-dimensional list to understand and analyze.

This is a screenshot of the middle process of the game (without the function of checking and cleaning)

At this time, the two-dimensional list corresponding to the square panel in the game panel is as follows.

board = [
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', 'L', '', '', '', ''],
['', '', '', '', '', 'L', 'L', 'L', '', '', '', ''],
['', '', 'I', '', 'Z', 'Z', 'Z', 'Z', '', '', '', 'Z'],
['', 'T', 'I', 'I', 'S', 'Z', 'Z', 'Z', 'Z', '', 'Z', 'Z'],
['T', 'T', 'I', 'I', 'S', 'S', 'S', 'T', 'T', 'T', 'Z', 'L'],
['J', 'T', 'I', 'I', 'J', 'S', 'S', 'S', 'T', 'L', 'L', 'L'],
['J', 'J', 'J', 'I', 'J', 'J', 'J', 'S', 'I', 'I', 'I', 'I']
]

This is a two-dimensional list of 20x12 (20 rows and 12 columns).

The '' empty string corresponds to a blank grid.
The letters' o ','s','t', 'I', 'l', 'J', 'Z' correspond to different kinds of Tetris,
There are different colors.

### 3. Quickly create a 2D list

#### Use list generation

Create a binary list of empty strings with 3 rows and 4 columns.

board = [
["" for ci in range(4)] for ri in range(3)
]

The board is as follows

[
['', '', '', ''],
['', '', '', ''],
['', '', '', '']
]

#### Use two-layer cycle

Create a binary list of empty strings with 3 rows and 4 columns.

board = []
for ri in range(3):
row = []
for ci in range(4):
row.append("")
board.append(row)

The board is as follows

[
['', '', '', ''],
['', '', '', ''],
['', '', '', '']
]

### 4 using nested lists

#### Tic tac toe detection

Take the example given above as an example

board = [
["X", "X", "X"],
["O", "X", " "],
["O", " ", "O"],
]

We can see that the player corresponding to "X" won.
So can you implement a program to judge which player won?

Specifically, implement a function get_ttt_winner(board)，
Accept a 3x3 two-dimensional list board as the parameter,
Return the winning player's chess symbols: "X", "O", "no one wins".
Add: ttt is because tic tac toe corresponds to tic tac toe...

Train of thought analysis:
At this time, you need to check all rows, all columns, and two diagonals.
These are essentially a string of three lattices.

Then a corresponding sub function check is designed here_ bunch_ match(bunch, symbol).
It can check whether a bunch composed of three grids is a player's chess symbol.
Such a function to solve the sub problems in the total problem is often called the auxiliary function help function.

def check_bunch_match(bunch, symbol):
res = True
for one in bunch:
if one != symbol:
res = False
break

return res

Then the main function is easier to write.
get_ttt_winner(board)
The implementation code is as follows

def get_ttt_winner(board):
r, c = len(board), len(board[0])
for symbol in "XO":
for ri in range(r):
row = board[ri]
if check_bunch_match(row, symbol):
return symbol

for ci in range(c):
column = [board[ri][ci] for ri in range(r)]
if check_bunch_match(column, symbol):
return symbol

diagonal_1 = [board[ri][ri] for ri in range(r)]
diagonal_2 = [board[ri][c-ri-1] for ri in range(r)]
if check_bunch_match(diagonal_1, symbol):
return symbol
if check_bunch_match(diagonal_2, symbol):
return symbol

return "N"

The call statement is as follows

board = [
["X", "X", "X"],
["O", "X", " "],
["O", " ", "O"],
]

r = get_ttt_winner(board)
print(r)

The output is as follows

X

#### Tetris detection

In the Tetris example given above, the check and clean-up function is not implemented.
Then let's implement this function.

Specifically, implement a function check_and_clear(board)，
Accept a two-dimensional list board as a parameter (the number of rows and columns of board is uncertain, but they are greater than 0),
Check whether there are rows filled with Russian squares, and clean them if there are,
Operate directly on the board without returning.

In order to make it easy to see the effect, the board is directly displayed in a highly readable format after cleaning in the function.
The empty grid is displayed as, The grid with Tetris is displayed with the corresponding characters of the box.

Train of thought analysis:
A subfunction check is required_ row_ Complete (row) to check whether a row is filled.

def check_row_complete(row):
for cell in row:
if cell=='':
return False

return True

Then the main function check_ and_ The clear (board) is as follows:

def check_and_clear(board):
has_complete_row = False
r, c = len(board), len(board[0])
for ri in range(r):
if check_row_complete(board[ri]):
# The current line can be eliminated
if ri > 0:
for cur_ri in range(ri, 0, -1):
board[cur_ri] = board[cur_ri-1][:]
board[0] = ['' for j in range(c)]
else:
board[ri] = ['' for j in range(c)]

# display
for row in board:
for cell in row:
if cell:
print(cell, end="")
else:
print("_", end="")

print()

The calling code is as follows

board = [
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', 'L', '', '', '', ''],
['', '', '', '', '', 'L', 'L', 'L', '', '', '', ''],
['', '', 'I', '', 'Z', 'Z', 'Z', 'Z', '', '', '', 'Z'],
['', 'T', 'I', 'I', 'S', 'Z', 'Z', 'Z', 'Z', '', 'Z', 'Z'],
['T', 'T', 'I', 'I', 'S', 'S', 'S', 'T', 'T', 'T', 'Z', 'L'],
['J', 'T', 'I', 'I', 'J', 'S', 'S', 'S', 'T', 'L', 'L', 'L'],
['J', 'J', 'J', 'I', 'J', 'J', 'J', 'S', 'I', 'I', 'I', 'I']
]

check_and_clear(board)

The output is as follows

____________
____________
____________
____________
____________
____________
____________
____________
____________
____________
____________
____________
____________
____________
____________
____________
_______L____
_____LLL____
__I_ZZZZ___Z
_TIISZZZZ_ZZ

### 5 brief review

#### Common syntax of two-dimensional list

Get the total number of rows and columns.

r = len(board)
c = len(board[0])

Get the contents of line ri and ci: board[ri][ci]

Posted by lesliesathish on Wed, 01 Dec 2021 03:36:32 -0800