[英]Using a vector to subset elements within a string vector in Julia
我正在尝试使用Integer
和Vector{Integer}
子集值的组合在Julia中对Vector{String}
进行子集化。 我想编写一个函数,它基本上允许"asdf"[1:3]
的子集,三个参数x[y:z]
中的每一个都是向量或单例。
这是我到目前为止所尝试的:
function substring(x::Array{String}, y::Integer, z::Integer)
y = fill(y, length(x))
z = fill(z, length(x))
substring(x, y, z)
end
function substring(x::Vector{String}, y::Vector{Integer}, z::Integer)
y = fill(y, length(x))
substring(x, y, z)
end
function substring(x::Vector{String}, y::Integer, z::Vector{Integer})
z = fill(z, length(x))
substring(x, y, z)
end
function substring(x::Vector{String}, y::Vector{Integer}, z::Vector{Integer})
for i = 1:length(x)
x[i] = x[i][y[i]:min(z[i], length(x[i]))]
# If z[i] is greater than the length of x[i]
# return the end of the string
end
x
end
试图使用它:
v = string.('a':'z')
x = rand(v, 100) .* rand(v, 100) .* rand(v, 100)
substring(x, 1, 2)
# or
substring(x, 1, s)
我收到错误:
MethodError: no method matching substring(::Array{String,1}, ::Int64, ::Array{Int64,1})
Closest candidates are:
substring(::Array{String,N}, ::Integer, !Matched::Integer) at untitled-e3b9271a972031e628a35deeeb23c4a8:2
substring(::Array{String,1}, ::Integer, !Matched::Array{Integer,1}) at untitled-e3b9271a972031e628a35deeeb23c4a8:13
substring(::Array{String,N}, ::Integer, !Matched::Array{Integer,N}) at untitled-e3b9271a972031e628a35deeeb23c4a8:13
...
in include_string(::String, ::String, ::Int64) at eval.jl:28
in include_string(::Module, ::String, ::String, ::Int64, ::Vararg{Int64,N}) at eval.jl:32
in (::Atom.##53#56{String,Int64,String})() at eval.jl:50
in withpath(::Atom.##53#56{String,Int64,String}, ::Void) at utils.jl:30
in withpath(::Function, ::String) at eval.jl:38
in macro expansion at eval.jl:49 [inlined]
in (::Atom.##52#55{Dict{String,Any}})() at task.jl:60
我看到有另一篇文章解决类型为Vector{String}
的类似错误。 我的帖子还质疑对与Vector{Integer}
相关的错误的回应。 我相信对它的反应可能对像我这样的人来说有帮助,他们发现抽象类型的实现既新颖又困难。
如果你使用的是Julia 0.6,使用SubString.(strs, starts, ends)
很容易做到SubString.(strs, starts, ends)
:
julia> SubString.("asdf", 2, 3)
"sd"
julia> SubString.(["asdf", "cdef"], 2, 3)
2-element Array{SubString{String},1}:
"sd"
"de"
julia> SubString.("asdf", 2, [3, 4])
2-element Array{SubString{String},1}:
"sd"
"sdf"
在Julia 0.5上,你可以做同样的事情,但你必须将字符串包装在一个向量中(即它不能保留为单个标量):
julia> SubString.(["asdf"], [1, 2, 3], [2, 3, 4])
3-element Array{SubString{String},1}:
"as"
"sd"
"df"
Julia和R之间的主要区别在于,在R中,默认情况下,函数通常用于向量(广播),在Julia中,您通过使用所谓的“点调用”(即f.(x, y, z)
)明确指定广播行为f.(x, y, z)
。
只是为了明确这一点,认为这是一个非常普遍的想法。
即使Int64 <: Integer
是真的
Array{Int64,1} <: Array{Integer,1}
不是!
参数复合类型的文档详细解释了原因。 但是为了解释它,主要是因为前一个Array{Int64,1}
在内存中有一个特定的表示(即许多连续的64位值),而Array{Integer,1}
必须是指向可能或可能的单独分配值的指针集。不是64位。
请参阅类似的Q&A,了解可用于在julia中声明函数的酷新语法0.6 w /关于此: Vector {AbstractString}函数参数不接受julia中的Vector {String}输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.