全局变量未更新:10*22二维列表矩阵调用函数后未修改
Hey there! Let's dig into why your matrix isn't updating after calling your step function—this is a super common gotcha with Python lists, so we'll fix it in no time.
First, let's recap your goal: you have a 10x22 matrix initialized with dots (.), and you want to convert any row that has no dots at all into a full row of dots. The problem is that after running your step function, the original matrix stays unchanged.
The Most Likely Culprit: Incorrect Row Modification
In Python, when you loop through a list like for row in matrix, the row variable is just a reference to the original row in the matrix. If you reassign row to a new list (like row = ['.'] * WIDTH), you're only changing what that local variable points to—not the actual row stored in the matrix.
Example of the Wrong Approach
This is probably what your step function looks like right now, and it won't modify the original matrix:
def step(mat): for row in mat: if '.' not in row: # Check if the row has no dots row = ['.'] * WIDTH # This only updates the local 'row' variable, not the matrix!
The Fix: Modify the Matrix via Indexes
Instead of reassigning the loop variable, access each row by its index in the matrix and replace it directly. This ensures you're modifying the original matrix object.
Working Step Function
def step(mat): # Loop through each row index for i in range(len(mat)): current_row = mat[i] # Check if this row has no dots if '.' not in current_row: # Replace the row in the original matrix with a full dot row mat[i] = ['.'] * WIDTH
Full Working Code Example
Here's how it all fits together, including initialization and verification:
WIDTH, HEIGHT = 10, 22 # Initialize matrix with all dots matrix = [['.' for x in range(WIDTH)] for y in range(HEIGHT)] # Simulate some rows without dots (replace this with your actual middle logic) matrix[3] = ['X'] * WIDTH matrix[7] = ['#'] * WIDTH # Your fixed step function def step(mat): for i in range(len(mat)): if '.' not in mat[i]: mat[i] = ['.'] * WIDTH # Run the step function step(matrix) # Print the updated matrix to verify for row in matrix: print(''.join(row))
Double-Check Your Logic
If the fix above doesn't work, make sure your condition is correct:
- You want
if '.' not in rowto target rows with no dots - If you accidentally wrote
if '.' in row, you'd be modifying rows that do have dots, which won't match your goal
内容的提问来源于stack exchange,提问作者Karan Singh

