You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化绘图程序的重复坐标判断代码?能否使用range函数?

Simplifying Your Repetitive Drawing Code

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 if blocks, 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 grid and col_headers—no need to rewrite dozens of lines.

内容的提问来源于stack exchange,提问作者dov lowinger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:17:59