如何简化绘图程序的重复坐标判断代码?能否使用range函数?
Absolutely! You can ditch all that tedious repetitive if block code by leveraging Python's data structures and string parsing. Let's refactor your code step by step to make it clean, scalable, and way less of a hassle.
Step 1: Replace Individual Row Variables with a 2D List
Instead of having separate L0 to L9 variables, store your grid rows in a single 2D list. This makes accessing any row or cell dynamic and straightforward:
# Define your grid as a 2D list (rows 0-9) grid = [ ['0', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['1', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['2', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['3', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['4', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['5', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['6', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['7', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['8', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ['9', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'], ] # Column headers (a-j map to indices 1-10) col_headers = ['/', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Step 2: Simplify the all() Function
Now you can rewrite your all() function to loop through the grid instead of printing each row manually:
def all(): print(*col_headers) for row in grid: print(*row)
Step 3: Parse Input Dynamically (No More 100 if Blocks!)
Instead of checking every possible coordinate with an if statement, write a function to parse user input and map it to the correct grid position. We'll also add delete support in one go:
def parse_input(user_input): # Check if this is a delete command (e.g., "-a0" or "del a0") delete_mode = False cleaned_input = user_input.strip().lower() if cleaned_input.startswith('-'): delete_mode = True coord = cleaned_input[1:] elif cleaned_input.startswith('del '): delete_mode = True coord = cleaned_input[4:] else: coord = cleaned_input # Validate coordinate format (must be 2 characters: letter + number) if len(coord) != 2: return None, None, delete_mode col_char, row_char = coord[0], coord[1] # Map column letter to grid index (a=1, b=2, ..., j=10) # Use a dictionary for fast lookups instead of list.index() col_map = {char: idx for idx, char in enumerate(col_headers) if idx != 0} col_idx = col_map.get(col_char) # Map row number to grid index (0=0, 1=1, ..., 9=9) try: row_idx = int(row_char) if not (0 <= row_idx < len(grid)): row_idx = None except ValueError: row_idx = None return row_idx, col_idx, delete_mode
Step 4: Main Loop to Handle Input
Use a loop to continuously accept input, parse it, and update the grid:
# Initial grid render all() print('\nEnter coordinates to draw (use "-a0" or "del a0" to delete, type "quit" to exit)') while True: user_input = input() if user_input.lower() == 'quit': print("Exiting program...") break row_idx, col_idx, delete_mode = parse_input(user_input) # Handle invalid input if row_idx is None or col_idx is None: print("Invalid input! Please use format like 'a0' (draw) or '-a0' (delete).") continue # Update the grid: set to 'x' or '.' grid[row_idx][col_idx] = '.' if delete_mode else 'x' # Redraw the grid print('\n') all()
Why This Works
- No repetitive code: Instead of writing 100
ifblocks, we dynamically parse input to find the right grid position. - Easy delete support: We just check for a prefix in the input to toggle delete mode—no extra code needed.
- Scalable: If you ever expand the grid (e.g., add rows 10-15 or columns k-o), you only need to update the
gridandcol_headers—no need to rewrite dozens of lines.
内容的提问来源于stack exchange,提问作者dov lowinger

