julia - 塑造 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
解决方案
我会用[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
推荐阅读
- javascript - codeigniter 在按钮单击和显示时启动计时器
- vue.js - 传统网站如何搭建Vue(jquery替换)
- c++ - GCC STL 是否具有从 typedef 别名获取原始类型的特征?
- javascript - JS奇数之和迷路了?
- python - 防止私有和基于 pypi 的 Python 包之间的命名空间冲突
- comparison-operators - 比较 gdscript 中的浮点数时,运算符“<”中的操作数“bool”和“float”无效
- android - 在应用程序启动时自动调用库函数
- swift - Swift 数据类型列表
- performance - wxPython FloatCanvas 事件绑定
- java - 无法使用 Java 对我的 PostgreSQL 数据库进行提交