Python实现支持双参数的可变大小网格打印函数求助
Hey there! Let's build out that two-parameter version of your grid printer. First, let's align on intuitive definitions for each parameter (since your description cut off mid-explanation, I'll go with a common logical setup—feel free to tweak if you had something specific in mind):
- x: The number of rows/columns in the overall grid (e.g., x=3 creates a 3x3 grid of individual cells)
- y: The size of each individual cell (e.g., y=7 means each cell has 7 dashes in horizontal lines and 7 spaces between vertical bars)
Recap of Your Single-Parameter Logic
Your print_grid(15) outputs a 2x2 grid where each cell is size 7—this makes sense because 15 = 2*(7+1) + 1 (the extra + signs account for the grid borders). The two-parameter version will let us decouple the grid's dimensions from the cell size for full flexibility.
Full Two-Parameter Implementation
Here's a clean, readable implementation that matches your existing output style:
def print_grid(x, y): # Create the horizontal segment for one cell (e.g., "+ ------- " for y=7) cell_horizontal = f"+ {'-' * y} " # Build the full horizontal line by repeating the cell segment x times, then add a final "+" horizontal_line = cell_horizontal * x + "+" # Create the vertical segment for one cell (e.g., "| " for y=7) cell_vertical = f"| {' ' * y} " # Build the full vertical line by repeating the cell segment x times, then add a final "|" vertical_line = cell_vertical * x + "|" # Construct the grid: repeat "horizontal line + y vertical lines" x times for _ in range(x): print(horizontal_line) # Print y vertical lines for each row of cells for _ in range(y): print(vertical_line) # Print the final horizontal line to close the grid print(horizontal_line)
How It Works
Let's break down the key pieces:
- Horizontal Borders: We first define a single cell's horizontal edge, then repeat it to form the full top/bottom of a grid row.
- Vertical Lines: Similarly, a single cell's vertical segment is repeated to create the lines between horizontal borders.
- Grid Assembly: For each row in the overall grid, we print one horizontal border followed by y vertical lines. We finish with a final horizontal border to cap off the grid.
Example Usage & Output
Calling print_grid(2, 7) will produce exactly the output you shared for print_grid(15):
| | |
| | |
Another test: print_grid(3, 4) creates a 3x3 grid with smaller cells:
- ---- + ---- + ---- +
| | | |
| | | |
| | | |
| | | |- ---- + ---- + ---- +
| | | |
| | | |
| | | |
| | | |- ---- + ---- + ---- +
| | | |
| | | |
| | | |
| | | |- ---- + ---- + ---- +
Customization Tip
If you intended x and y to represent different values (like x=cell width, y=grid row count), you can easily swap the logic—just adjust which parameter controls the repetition count vs. cell size. The core structure stays the same!
内容的提问来源于stack exchange,提问作者McBraunie

