Python如何将9x9数独嵌套列表按指定网格格式打印输出
直接替换你现有的formatted_board函数为以下实现即可匹配要求的打印格式:
def formatted_board(): # 打印顶部列号 print(" 0 1 2 3 4 5 6 7 8 ") # 通用横向分割线 separator = " +-------+-------+-------+" print(separator) # 逐行输出棋盘内容 for row_idx in range(9): line = f"{row_idx} |" for col_idx in range(9): line += f" {board[row_idx][col_idx]}" # 每3列添加竖线分隔 if (col_idx + 1) % 3 == 0: line += " |" print(line) # 每3行添加横向分割线 if (row_idx + 1) % 3 == 0: print(separator)
如果需要避免输入的行、列超出0-8范围导致数组索引报错,也可以同步优化choose_cell函数的校验逻辑:
def choose_cell(): try: row = int(input("choose row(0-8):")) column = int(input("choose column(0-8):")) choose_num = int(input("choose a num between 1 and 9:")) if 0 <= row <= 8 and 0 <= column <=8 and 0 < choose_num <=9: board[row][column] = choose_num formatted_board() else: print("illegal input try again") choose_cell() except ValueError: print("please enter valid integer") choose_cell()
内容的提问来源于stack exchange,提问作者Shushue
相关产品推荐
相关产品推荐

