Select 个不属于基本 Julia 整数列表的元素
Select elements that are not a part of an integer list in base Julia
如果我有一个 Float64 向量 Y 和一个整数向量 x,例如 x=rand(1:1000, 500),是否有一种优雅的方法可以在非 x 条目处提取 Y 的元素?到目前为止,我已经尝试了 Y[findall([i ∉ x for i in 1:1000])]
。这行得通,但是来自 R,我希望做一些像 Y[.!x]
或 Y[!x]
这样的事情,它们都会抛出错误。我想避免使用像 DataFrames 这样的包,但如果这不可能,我理解。
提前致谢。
使用 InvertedIndices
中的 Not
(这也会通过 DataFrames
导入)。
在您的情况下,这是 Y[Not(x)]
,请参阅下面的代码:
julia> using InvertedIndices # or using DataFrames
julia> Y = collect(1:0.5:4)
7-element Vector{Float64}:
1.0
1.5
2.0
2.5
3.0
3.5
4.0
julia> x=rand(1:7, 3)
3-element Vector{Int64}:
3
2
6
julia> Y[Not(x)]
4-element Vector{Float64}:
1.0
2.5
3.0
4.0
由于问题明确要求不依赖标准库之外的包的解决方案,这里是 的替代方案:
Y[∉(x).(1:length(Y))]
这里我们使用∉
的部分应用形式。来自 in
的文档:
in(collection)
∈(collection)
Create a function that checks whether its argument is in collection
,
i.e. a function equivalent to y -> y in collection
.
同样的东西可以有几种不同的写法,例如Y[eachindex(Y) .∉ Ref(x)]
(适用于这种情况,但您应该理解 eachindex
and have a look at LinearIndices
and CartesianIndices
)。
需要注意的重要一点是,当 x
很大时,这些解决方案的性能不佳。为了提高性能,可以从 x
创建 Set
。示例:
Y[∉(Set(x)).(eachindex(Y))]
如果我有一个 Float64 向量 Y 和一个整数向量 x,例如 x=rand(1:1000, 500),是否有一种优雅的方法可以在非 x 条目处提取 Y 的元素?到目前为止,我已经尝试了 Y[findall([i ∉ x for i in 1:1000])]
。这行得通,但是来自 R,我希望做一些像 Y[.!x]
或 Y[!x]
这样的事情,它们都会抛出错误。我想避免使用像 DataFrames 这样的包,但如果这不可能,我理解。
提前致谢。
使用 InvertedIndices
中的 Not
(这也会通过 DataFrames
导入)。
在您的情况下,这是 Y[Not(x)]
,请参阅下面的代码:
julia> using InvertedIndices # or using DataFrames
julia> Y = collect(1:0.5:4)
7-element Vector{Float64}:
1.0
1.5
2.0
2.5
3.0
3.5
4.0
julia> x=rand(1:7, 3)
3-element Vector{Int64}:
3
2
6
julia> Y[Not(x)]
4-element Vector{Float64}:
1.0
2.5
3.0
4.0
由于问题明确要求不依赖标准库之外的包的解决方案,这里是
Y[∉(x).(1:length(Y))]
这里我们使用∉
的部分应用形式。来自 in
的文档:
in(collection)
∈(collection)
Create a function that checks whether its argument is
in collection
, i.e. a function equivalent toy -> y in collection
.
同样的东西可以有几种不同的写法,例如Y[eachindex(Y) .∉ Ref(x)]
(适用于这种情况,但您应该理解 eachindex
and have a look at LinearIndices
and CartesianIndices
)。
需要注意的重要一点是,当 x
很大时,这些解决方案的性能不佳。为了提高性能,可以从 x
创建 Set
。示例:
Y[∉(Set(x)).(eachindex(Y))]