contexts
I've been learning Python recently, and I think the best way to learn a new language is to write a simple project, so I was going to write a simple Tetris game. Then in the process of writing it I encountered a small problem.
def __init__(self, width = 10, height = 30): , = width, height self.board_size = [width, height]
I'm using a 2D List to record the state of the game space. game_boardx represents a grid, 0 means the grid is empty, 1 means it is not. Obviously, the initialization should assign all the grids to 0. After looking up the documentation on Lists, I found that you can use [0] * n to quickly create a List of a specific length, so it's natural to write the following line of code.
self.game_board = [[0] * height] * width
Check the results, indeed created the length and width of the expected, the value of all 0 of a two-dimensional List, do not feel any problem, and then went on to write the next.
concern
However, when I was writing the elimination method in the past two days, I used the bottom 3 rows to be all 1s, and the center of the 4th row to be 1s and the rest all 0s, so that after the elimination is complete, there should still be 1 1 left to fall to the first row. But during the testing process, I found that no matter what, all the 1's were eliminated. At first I thought there was a problem with the elimination algorithm, but then I realized that when there was a value of 1 in a horizontal row, all the values in this horizontal row would automatically become 1.
settle (a dispute)
It's natural to think that this is generated by a reference to a List object. [0] * height produces a List of length height and all 0's, and since 0 is an int, which is the base datatype, this is the correct way to use it. But when you use this List to * width operation, it is the reference of this List that is generated, not a new width List, so if you modify any one of them, all of them will be modified.
After consulting the Python documentation, the code was modified to:
self.game_board = [([0] * height) for i in range(width)]
Testing identifies problem solving.
Approach to creating two-dimensional arrays
direct creation method
test = [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Simple and brutal, but too much of a hassle and generally not used.
list generating method
test = [[0 for i in range(m)] for j in range(n)]
Learn to use list generators for a lifetime.
Use the module numpy to create
import numpy as np test = ((m, n), dtype=)
summarize
It's a very basic question, I don't know enough about the Python * operator, so I took it for granted that it represents a deep copy of an object. And maybe I've done more front-end work and I'm less sensitive to the basics of data structures, so I'd better practice more.
This is the whole content of this article.