删除 julia 数组中的元素 [英] Delete element in an array for julia
问题描述
我在文档和论坛中徘徊了一段时间,但我还没有找到一个内置的方法/函数来完成删除数组中元素的简单任务.有这样的内置功能吗?
I've been wandering for a while in the docs and in forums and I haven't found a built in method/function to do the simple task of deleting an element in an array. Is there such built-in function?
我要求相当于 python 的 list.remove(x).
I am asking for the equivalent of python's list.remove(x).
这是一个天真地从框中挑选函数的示例:
Here's an example of naively picking a function from the box:
julia> a=Any["D","A","s","t"]
julia> pop!(a, "s")
ERROR: MethodError: `pop!` has no method matching
pop!(::Array{Any,1}, ::ASCIIString)
Closest candidates are:
pop!(::Array{T,1})
pop!(::ObjectIdDict, ::ANY, ::ANY)
pop!(::ObjectIdDict, ::ANY)
...
这里提到使用deleteat!
,但也不起作用:
Here mentions to use deleteat!
, but also doesn't work:
julia> deleteat!(a, "s")
ERROR: MethodError: `-` has no method matching -(::Int64, ::Char)
Closest candidates are:
-(::Int64)
-(::Int64, ::Int64)
-(::Real, ::Complex{T<:Real})
...
in deleteat! at array.jl:621
推荐答案
你也可以用 filter!
:
a = Any["D", "A", "s", "t"]
filter!(e->e≠"s",a)
println(a)
给予:
Any["D","A","t"]
这允许一次删除多个值,如:
This allows to delete several values at once, as in:
filter!(e->e∉["s","A"],a)
注意 1:在 Julia 0.5 中,匿名函数要快得多,并且在 0.4 中感受到的小惩罚不再是问题 :-).
Note 1: In Julia 0.5, anonymous functions are much faster and the little penalty felt in 0.4 is not an issue anymore :-) .
注意 2:上面的代码使用 unicode 运算符.使用普通运算符:≠
是 !=
并且 e∉[a,b]
是 !(e in [a,b])
Note 2: Code above uses unicode operators. With normal operators: ≠
is !=
and e∉[a,b]
is !(e in [a,b])
这篇关于删除 julia 数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!