【发布时间】:2019-02-22 16:36:21
【问题描述】:
我有一个列表t,其中包含平方数的元素,例如16、25、400。
现在想创建一个 numpy 数组 a 充满零,大小相同但呈方形,例如4x4、5x5、20x20。
我找到了解决办法:
a = np.zeros(2 * (int(np.sqrt(len(t))),))
或
a = np.zeros(len(t)).reshape(int(np.sqrt(len(t))), int(np.sqrt(len(t))))
它正在工作,但它非常难看,我相信一定有更好的方法来做到这一点。
像a = np.zeros(t, 2) 这样的东西。
有什么想法吗?
谢谢! :)
【问题讨论】:
-
你的第一个建议是你能做到的最短的。如果不可读,提取一个
square_shape(length)函数,并使用np.zeros(square_shape(len(l)))
标签: python arrays list numpy reshape