I got a python sublist and a function(replace 0 with .) to print this sublist(Yeah, it's like sudoku). The code is as below.
grid = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] def print_grid(): for row in grid: for column in row: if column == 0: print("." , end=" ") else: print(column , end=" ")
After I run print_grid(), I got a result like below. I wonder how to print it line by line. Thanks in advance for any kind of help.
3 . . 7 . . . . 6 . . 1 9 5 . . . . 9 8 . . . . 6 . 8 . . . 6 . . . 3 4 . . 8 . 3 . . 1 7 . . . 2 . . . 6 . 6 . . . . 2 8 . . . . 4 1 9 . . 5 . . . . 8 . . 7 9
Add a print()
at the end of second for loop:
grid = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
def print_grid():
for row in grid:
for column in row:
if column == 0:
print("." , end=" ")
else:
print(column , end=" ")
print()
print_grid()
This achieves the result you are looking for in a simpler way, printing each row of the grid "line by line". For each row we use a list comprehension to generate a new list of the row values where 0 is replaced with "." Then using the splat operator (*) we pass this row as arguments which the print statement will print with spaces in between.
grid = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
for row in grid:
print(*["." if val == 0 else val for val in row])
The module Numpy
is perfect for this. But also it is required that your print function becomes a board modifying function.
grid = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
def change_grid():
for x in range(9):
for y in range(9):
if grid[x][y] == 0:
grid[x][y] = "."
change_grid()
print(np.matrix(grid))
All you need to do is to change a line everytime you loop through one row.
def print_grid():
for row in grid:
print("")
for column in row:
if column == 0:
print("." , end=" ")
else:
print(column , end=" ")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.