因此,文本 file 看起来像这样: [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3 ]]
问题是如何读取该行并使其成为具有 5 行和 3 列的二维数组?我已经尝试过这段代码,但出现了这个错误“ValueError:无法将大小为 1 的数组重塑为形状 (5,3)”
file = open("test.txt", "r")
allocation = np.array(file.readline())
all = np.reshape(allocation, (5,3))
print(allocation)
file.close()
抱歉,如果之前已经提出过这个问题,但我不太了解其他解决方案。谢谢你。
回答1
一种直接的方法使用 eval()
函数:
inp = "[[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]"
arr = eval(inp)
print(arr) # [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]
print(arr[1][1]) # 2