删除julia数组中的元素

use*_*579 17 arrays julia

我已经在文档和论坛中徘徊了一段时间,我还没有找到一个内置的方法/函数来完成删除数组中元素的简单任务.有这样的内置功能吗?

我要求相当于python的list.remove(x).

这是一个天真地从框中选择一个函数的例子:

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)
  ...
Run Code Online (Sandbox Code Playgroud)

这里提到使用 deleteat!,但也不起作用:

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
Run Code Online (Sandbox Code Playgroud)

Dan*_*etz 12

你也可以选择filter!:

a = Any["D", "A", "s", "t"]
filter!(e->e?"s",a)
println(a)
Run Code Online (Sandbox Code Playgroud)

得到:

Any["D","A","t"]
Run Code Online (Sandbox Code Playgroud)

这允许一次删除多个值,如:

filter!(e->e?["s","A"],a)
Run Code Online (Sandbox Code Playgroud)

注1:在Julia 0.5中,匿名函数更快,0.4中的小惩罚不再是问题:-).

注2:上面的代码使用unicode运算符.与普通运营商:?!=e?[a,b]!(e in [a,b])


amr*_*ods 9

deleteat!+ findin会这样做:

a = Any["D", "A", "s", "t"]
deleteat!(a, findin(a, ["s"])) # => ["D", "A", "t"]
Run Code Online (Sandbox Code Playgroud)

这是因为pop!没有消除Array中特定元素的方法,它只消除了最后一个deleteat!元素,并且需要你想要消除的元素的索引.您可以检查函数具有的方法methods:

methods(pop!)
methods(deleteat!)
Run Code Online (Sandbox Code Playgroud)

对于a Dict,您可以提供元素的键以消除delete!.


张实唯*_*张实唯 5

根据使用情况,了解它也是很好的setdiff,它是就地版本setdiff!

julia> setdiff([1,2,3,4], [3])
3-element Array{Int64,1}:
 1
 2
 4
Run Code Online (Sandbox Code Playgroud)

但是,请注意,它还会删除所有重复的元素,如示例所示:

julia> setdiff!([1,2,3,4, 4], [3])
3-element Array{Int64,1}:
 1
 2
 4
Run Code Online (Sandbox Code Playgroud)


Nos*_*All 5

朱莉娅的最新版本已弃用了其他几个答案。我目前(Julia 1.1.0)使用类似

function remove!(a, item)
    deleteat!(a, findall(x->x==item, a))
end
Run Code Online (Sandbox Code Playgroud)

您也可以根据需要使用findfirst,但如果a不包含,则无法使用item