我要创建一个单行衬里,根据一组值过滤一个数组。这意味着我想遍历 A 的每个元素并与 B 的元素进行比较。
例如:什么是安全的饮料?
A = ["water";"beer";"ammonia";"bleach";"lemonade"]
B = ["water";"beer"; "lemonade"]
Run Code Online (Sandbox Code Playgroud)
我把这个怪物放在一起,但是,我希望有人有一个更优雅的方法:
julia> vcat(filter(w->length(w)!= 0, map(y->filter(z->z!="",(map(x-> begin x==y ? x = y : x = "" end,B))),A))...)
3-element Array{String,1}:
"water"
"beer"
"lemonade"
Run Code Online (Sandbox Code Playgroud) 我做了一个查找球体体积的函数:
function volume_sphere(r)
(4/3)(round(?, sigdigits=6))(r)^3
end
julia> println(volume_sphere(5))
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
错误:MethodError:类型为Float64的对象不可调用
Stacktrace:
[1] volume_sphere(:: Int64)在C:\ Users \ Practice.jl:27
[2]顶级作用域为none:0
问题出在哪里?
当创建各种大小的向量数组(例如数组)时,我正在生成错误消息。
julia> A = [[1,2] [1,2,3] [1,4] [1] [1,5,6,7]]
ERROR: DimensionMismatch("vectors must have same lengths")
Stacktrace:
[1] hcat(::Array{Int64,1}, ::Array{Int64,1}, ::Array{Int64,1}, ::Vararg{Array{Int64,1},N} where N) at .\array.jl:1524
[2] top-level scope at none:0
Run Code Online (Sandbox Code Playgroud)
虽然,如果我初始化一个数组并为向量分配``没关系''...
julia> A = Array{Any}(undef,5)
5-element Array{Any,1}:
#undef
#undef
#undef
#undef
#undef
pseudo code> A[i] = [x,y...]
2-element Array{Int64,1}:
1
2
julia> A
5-element Array{Any,1}:
[1, 2]
[1, 2, 3]
[1]
[1, 5]
[1, 2, 6, 4, 5]
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以使用各种大小的数组来初始化数组,或者将Julia配置为防止错误的方法。
我正在尝试构建一个函数,该函数将输出要分配给新内存函数的表达式。我可能误解了元编程的能力,但是,我正在尝试构建一个函数来生成数学系列并将其分配给一个函数,例如:
主文件
function series(iter)
S = ""
for i in 1:iter
a = "x^$i + "
S = S*a
end
return chop(S, tail=3)
end
Run Code Online (Sandbox Code Playgroud)
所以,这将构建模式,我暂时在 repl 中使用它:
julia> a = Meta.parse(series(4))
:(x ^ 1 + x ^ 2 + x ^ 3 + x ^ 4)
julia> f =eval(Meta.parse(series(4)))
120
julia> f(x) =eval(Meta.parse(series(4)))
ERROR: cannot define function f; it already has a value
Run Code Online (Sandbox Code Playgroud)
显然 eval 在这种情况下不是我要找的,但是,我可以使用另一个函数吗?或者,这不是在 Julia 中完成任务的可行方法吗?