我正在开发一个函数来根据用户输入打印出一个网格。到目前为止,我能够打印出一个简单的版本,例如:
print_grid(15)
#prints a larger grid:
+ - - - - - - - + - - - - - - - +
| | |
| | |
| | |
| | |
| | |
| | |
| | |
+ - - - - - - - + - - - - - - - +
| | |
| | |
| | |
| | |
| | |
| | |
| | |
+ - - - - - - - + - - - - - - - +
但是现在我正在尝试做一些事情,以便它可以接受两个输入变量(x,y),其中x是行/列(区域)的数量,y是个体的大小,较大的网格是较大的网格整个。例如,print_grid2(3,4)导致:
+ - - - - + - - - - + - - - - +
| | | |
| | | |
| | | |
| | | |
+ - - - - + - - - - + - - - - +
| | | |
| | | |
| | | |
| | | |
+ - - - - + - - - - + - - - - +
| | | |
| | | |
| | | |
| | | |
+ - - - - + - - - - + - - - - +
我重复使用了第一个网格示例中的一些代码然后更改了它以尝试适应这个特定的任务,但这次我没有得到任何输出,如果我得到的话我不知道发生了什么没有什么作为输出...任何帮助表示赞赏。 (我还没有更新我的评论,所以我意识到它们不再有意义了,因为它们与之前的迭代有关)。
当前代码:
def grid_print(area, units):
print_Area = (area * area)
grid_rows = units + (units + 1) + 2
grid_cols = units + 2
if units % 2 == 0: # If grid entry is even (it will end up making
grid_rows += 1 # the square uneven, so increase number of rows by 1
# now grid is technically uneven
for i in range(print_Area):
for row in range(grid_rows): # for each item in number of items(rows)
for col in range(grid_cols): # for each item in number of items(columns)
if row == 0 or row == int(grid_rows/2) or row == grid_rows -1: # if item is beginning, middle or end
# -- Formatting beam structure -- #
if col == 0: # beginning, print '+' no '\n'
print('+', end='')
elif col == grid_cols -1: # end, print '+'
print('+')
elif int(grid_cols/2) == col: # middle:
if grid_rows % 2 == 0: # if grid is even, pad '+' with ' '
print(' + ', end='') # if grid is uneven, no padding
else: # print '+' no '\n'
print('+', end='')
elif col % 2 == 0: # if col item is an even number
print('-', end='') # print '-' with no '\n'
else: # else if col item is uneven item num
print(' ', end='') # print ' ' no '\n'
else:
# -- Formatting line structure -- #
if col == 0: # if column is at starting position 0
print('|', end='') # print '|' no '\n'
elif col == int(grid_cols/2): # if column is at middle pos
if units % 2 == 0: # print '|' no '\n'
print(' | ', end='') # (has padding if grid is even or not)
else:
print('|', end='')
elif col == grid_cols -1: # if column is at end position of grid
print("|") # print '|'
else:
print(' ', end='') # all other circumstances, print ' ' no '\n'
答案 0 :(得分:4)
因此在您的代码中可能只是if units % 2 == 0:
之后的缩进错误,但您的整个代码可以压缩到这些行:
def print_grid(area, unit):
for _ in range(area):
print(("+" + "- " * unit) * area + "+")
for _ in range(unit):
print(("|" + " " * unit) * area + "|")
print(("+" + "- " * unit) * area + "+")
print_grid(3, 4)
打印:
+--------+--------+--------+
| | | |
| | | |
| | | |
| | | |
+--------+--------+--------+
| | | |
| | | |
| | | |
| | | |
+--------+--------+--------+
| | | |
| | | |
| | | |
| | | |
+--------+--------+--------+