今天我在为一门课程做作业,作业是做一个tic tac toe板。可能性方法将tic tac toe板作为输入,并检查是否有任何值为"0",这意味着它是一个开放空间。我的计划是将0的位置添加到一个数组中,称为位置,然后在函数的末尾返回位置。但是,当我尝试将0的位置附加到位置数组时,我总是遇到这个问题:“拼接轴的所有输入数组维度必须完全匹配,但沿着维度0,索引0处的数组大小为2,索引1处的数组大小为1”。有人知道怎么解决这个问题吗?谢谢
import numpy as np
def create_board():
board = np.zeros((3,3), dtype = "int")
return board
def place(board, player, position):
x, y = position
board[x][y] = player
def posibilities(board):
locations = np.empty(shape=[2,0])
for i in range(len(board)):
for x in range(len(board[0])):
if board[i][x] == 0:
locations = np.append(locations, [[i,x]], axis=1)
print(locations)
posibilities(create_board())发布于 2020-08-10 23:45:08
正如@hpaulj建议的那样,使用list,并在末尾将其更改为np.array,即:
def posibilities(board):
locations = []
for i in range(len(board)):
for x in range(len(board[0])):
if board[i][x] == 0:
locations.append([[i,x]])
locations = np.array(locations) # or np.concatenate(locations) depending what you want
print(locations)这是正确的方式,因为python列表是可变的,而numpy数组不是。
发布于 2020-08-11 00:42:01
In [530]: board = np.random.randint(0,2,(3,3))
In [531]: board
Out[531]:
array([[0, 0, 0],
[1, 0, 1],
[0, 1, 0]])看起来您正在尝试收集黑板上它为0的位置。argwhere很好地做到了这一点:
In [532]: np.argwhere(board==0)
Out[532]:
array([[0, 0],
[0, 1],
[0, 2],
[1, 1],
[2, 0],
[2, 2]])使用列表追加:
In [533]: alist = []
In [534]: for i in range(3):
...: for j in range(3):
...: if board[i,j]==0:
...: alist.append([i,j])
...:
In [535]: alist
Out[535]: [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 2]]argwhere实际上使用np.nonzero来获取数组的元组,这些数组索引所需的位置。
In [536]: np.nonzero(board==0)
Out[536]: (array([0, 0, 0, 1, 2, 2]), array([0, 1, 2, 1, 0, 2]))通常,这个nonzero版本更容易使用。例如,它可以直接用于选择所有这些单元格:
In [537]: board[np.nonzero(board==0)]
Out[537]: array([0, 0, 0, 0, 0, 0])并将其中一些设置为1:
In [538]: board[np.nonzero(board==0)] = np.random.randint(0,2,6)
In [539]: board
Out[539]:
array([[0, 0, 1],
[1, 0, 1],
[1, 1, 1]])https://stackoverflow.com/questions/63343390
复制相似问题