问题描述
我正在终端中对Sudoku游戏进行编程,我想将网格打印到控制台,并在其周围有一个正方形,如下图所示.我的代码没有问题,但效率很低.
I'm Programming Sudoku game in terminal, I want to Print the grid to console with a square around it as in the picture below.There is no problem with my code except it is inefficient.
我想使其更高效,更短(具有列表理解,字符串乘法等功能).董事会是这样定义的,板= [[_代表范围(9)中的_] _代表范围(9)中的_]
I would like to get it more efficient and short (with list comprehensions, string multiplying, etc).the board is defined like that,board = [[_ for _ in range(9)] for _ in range(9)]
那是我正在使用的功能:
That is the function i'm using:
def Print_Board(board):
print("\n-------------------------")
for i in range(9):
for j in range(9):
if board[i][j] is not None:
if j == 0:
print("|", end=" ")
print(f"{board[i][j]} ", end="")
if (j + 1) % 3 == 0:
print("|", end=" ")
if (i + 1) % 3 == 0:
print("\n-------------------------", end=" ")
print()
推荐答案
您可以构建电路板格式并将所有数据投入其中:
You can build a board format and throw all the data at it:
bar = '-------------------------\n'
lnf = '|' +(' {:}'*3 + ' |')*3 + '\n'
bft = bar + (lnf*3+bar)*3
print(bft.format(*(el for rw in board for el in rw)))
当然,您只需要构建一次格式.之后,这只是打印.
You only need to build the format once, of course. After that it's just a print.
JonSG的注释建议将其封装在一个闭包中:
Suggestion from JonSG in comments to encapsulate this in a closure:
def make_board_printer():
bar = '-------------------------\n'
lnf = '|' +(' {:}'*3 + ' |')*3 + '\n'
bft = bar + (lnf*3+bar)*3
return (lambda bd:print(bft.format(*(el for rw in bd for el in rw))))
是返回板载打印机功能的函数:
is a function which returns a board printer function:
# make a printer:
b_print = make_board_printer()
# then as needed
b_print(board)
这篇关于如何更有效地打印Sudoku网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!