我将字符串转换为 numpy 数组并编写了以下函数:
def convert_to_array(puz, dim = 2, unknown = '_'):
holding_list = []
for i in range(len(puz)):
if puz[i] == unknown:
holding_list.append(0)
else:
holding_list.append(int(puz[i]))
if dim == 1:
return np.array(holding_list)
elif dim == 2:
return np.array(holding_list).reshape(9, 9)
如果用作独立函数,它会返回正确的 ndarray,但当我将其用作静态方法时,则不会。
class grid:
...
@staticmethod
def convert_to_array(puz, dim = 2, unknown = '_'):
holding_list = []
for i in range(len(puz)):
if puz[i] == unknown:
holding_list.append(0)
else:
holding_list.append(int(puz[i]))
if dim == 1:
return np.array(holding_list)
elif dim == 2:
return np.array(holding_list).reshape(9, 9)
当我拨打
print(grid.convert_to_array(SudokuPuzzle)
时,我会得到 ValueError: invalid literal for int() with base 10
。
对于上下文:我正在转换作为单行字符串文本 (puz) 输入的数独谜题。
我还尝试过 np.fromstring 和 np.frombuffer 按照其他线程中的建议将字符串转换为 numpy 数组。但这都不起作用。
作为类方法,签名需要稍微改变一下:
def convert_to_array(cls, puz, dim = 2, unknown = '_'):