board = []
for x in range(0,8):
board.append(["0"] * 8)
def print_board(board):
for row in board:
print(" ".join(row))
此代码创建了一个零位网格,但我希望将其中的5个替换为1,再将5个替换为两个
有人知道这样做的方法吗?
答案 0 :(得分:1)
如果您想随机设置一些带有“ 1”和“ 2”的坐标,则可以这样做:
import random
board = []
for x in range(0, 8):
board.append(["0"] * 8)
def print_board(board):
for row in board:
print(" ".join(row))
def generate_coordinates(x, y, k):
coordinates = [(i, j) for i in range(x) for j in range(y)]
random.shuffle(coordinates)
return coordinates[:k]
coo = generate_coordinates(8, 8, 10)
ones = coo[:5]
twos = coo[5:]
for i, j in ones:
board[i][j] = "1"
for i, j in twos:
board[i][j] = "2"
print_board(board)
输出
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0
0 0 2 0 0 0 0 0
1 0 0 0 2 0 0 0
0 0 0 0 2 0 0 2
2 0 0 0 0 0 0 1
注意:
random.seed(42)
,您可以将42
更改为所需的任何数字。generate_coordinates
接收x
(行数),y
(列数)和k(要选择的坐标数)。它会生成一个x * y坐标序列,将其洗牌并首先选择k
。最后,这会选择一个和两个的位置并更改值:
ones = coo[:5]
twos = coo[5:]
for i, j in ones:
board[i][j] = "1"
for i, j in twos:
board[i][j] = "2"