numpy追加函数出现问题



我今天正在为一门课程做作业,任务是创建一个井字板。可能性方法采用井字板作为输入,并检查是否有任何值为"0";0";,意味着这是一个开放的空间。我的计划是将0的位置添加到一个名为locations的数组中,然后在函数末尾返回locations。然而,当我试图将0的位置附加到locations数组时,我一直会遇到这样的问题:;连接轴的所有输入数组维度必须完全匹配,但沿着维度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())

As@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数组不是。

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]]

CCD_ 3实际上使用CCD_ 4来获得对所需位置进行索引的数组元组。

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]])

最新更新