3 回答
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
TA贡献1712条经验 获得超3个赞
假设您不想要numpy并且想要使用列表列表:
def string_to_matrix(str_in):
nums = str_in.split()
n = int(len(nums) ** 0.5)
return list(map(list, zip(*[map(int, nums)] * n)))
nums = str_in.split()由任何空格分割,n是结果的边长,map(int, nums)将数字转换为整数(从字符串),zip(*[map(int, nums)] * n)将数字分组为的组n,list(map(list, zip(*[map(int, nums)] * n)))将生成的元组转换zip为列表。
![?](http://img1.sycdn.imooc.com/54584d080001566902200220-100-100.jpg)
TA贡献1810条经验 获得超5个赞
假设你想让这个动态。
str_in = '1 2 3 4 5 6 7 8 9'
a = str_in.split(" ")
r_shape = int(math.sqrt(len(a)))
np.array([int(x) for x in a]).reshape(r_shape, r_shape)
![?](http://img1.sycdn.imooc.com/54584ef20001deba02200220-100-100.jpg)
TA贡献1865条经验 获得超7个赞
import numpy as np
def string_to_matrix(str_in):
str_in_split = str_in.split()
numbers = list(map(int, str_in_split))
size = r_shape = int(np.sqrt(len(numbers)))
return np.array(numbers).reshape(r_shape, r_shape)
这就是为什么你总是得到: AssertionError: None != ...
assertEqual(A, string_to_matrix("..."))验证是否A等于 string_to_matrix 返回的值。在您的代码中,您不返回任何内容,因此None
另一个问题是如何拆分字符串,更简单的选择是拆分所有内容并转换为数字,然后重新整形为 sqrt(元素数)。这假设输入长度可以被拆分以形成一个 nxn 矩阵
添加回答
举报