首页 > 解决方案 > 塑造 Julia 多维数组

问题描述

我是 Julia 的新手,正在创建一个形状正确的多维数组。

function get_deets(curric)
    curric = curric.metrics
    return ["" curric["complexity"][1] curric["blocking factor"][1] curric["delay factor"][1]] 
end

function compare_currics(currics...)
    headers = [" ", "Complexity", "Blocking Factor", "Delay Factor"]
    data = [get_deets(curric) for curric in currics]
     return pretty_table(data, headers)
end

我得到的数据是:

3-element Array{Array{Any,2},1}:
 ["" 393.0 184 209.0]
 ["" 361.0 164 197.0]
 ["" 363.0 165 198.0]

但是,我需要看起来像这样的东西:

3×4 Array{Any,2}:
 ""  393.0  184  209.0
 ""  361.0  164  197.0
 ""  363.0  165  198.0

标签: julia

解决方案


我会用[get_deets(curric) for curric in currics]减少来代替理解。

例如:

using Random

function getdeets(curric)
    # random "deets", as a 1-D Vector
    return [randstring(4), rand(), 10rand(), 100rand()]
end

function getdata(currics)
    # All 1-D vectors are concatenated horizontally, to produce a
    # 2-D matrix with "deets" as columns (efficient since Julia matrices
    # are stored in column major order)
    data = reduce(hcat, getdeets(curric) for curric in currics)
    return data
end

有了这个,你会得到一个与你想要的略有不同的结构:它是转置的,但总体上应该更有效

julia> getdata(1:3)
4×3 Array{Any,2}:
   "B2Mq"     "S0hO"      "6KCn"
  0.291359   0.00046518  0.905285
  4.03026    0.612037    8.6458
 35.3133    79.3744      6.49379


如果您希望您的表格数据以与您的问题相同的方式呈现,则可以轻松调整此解决方案:

function getdeets(curric)
    # random "deets", as a row matrix
    return [randstring(4) rand() 10rand() 100rand()]
end

function getdata(currics)
    # All rows are concatenated vertically, to produce a
    # 2-D matrix
    data = reduce(vcat, getdeets(curric) for curric in currics)
    return data
end

这会产生:

julia> getdata(1:3)
3×4 Array{Any,2}:
 "eU7p"  0.563626  0.282499  52.1877
 "3pIw"  0.646435  8.16608   27.534
 "AI6z"  0.86198   0.235428  25.7382

推荐阅读