【问题标题】:Numpy: Transform list into square arrayNumpy:将列表转换为方形数组
【发布时间】: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


【解决方案1】:

你可以试试:

shp = int(np.sqrt(len(l))
a = np.zeros((shp, shp))

【讨论】:

    【解决方案2】:

    你可以像这样清理它:

    size = len(l)
    sqrt = int(np.sqrt(size))
    a = np.zeros((sqrt, sqrt))
    

    任何时候你多次编写相同的代码片段,最好用变量、函数等替换。

    【讨论】:

    • 这是我第一次尝试的。但它的可读性太差了。而且这么小任务这么多变数,我也不喜欢^^
    猜你喜欢
    • 2017-03-08
    • 2019-08-30
    • 2015-01-07
    • 2017-10-19
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    相关资源
    最近更新 更多