如何从 julia 中的数组中删除每个第 n 个元素?假设我有以下数组:[116, 116]
并且我想要 a = [1 2 3 4 5 6]
在javascript中我会做类似的事情:
b = [1 2 4 5]
如何在 Julia 中完成?
答案 0 :(得分:4)
您的问题标题和文本提出了不同的问题。标题询问如何跳过第 N 个元素,而 Javascript 代码片段详细说明了如何根据元素的 value 而不是它们的索引来跳过元素。
我们可以使用 filter
来做到这一点。
filter((x) -> x % 3 != 0, a)
这基本上等同于您的 Javascript 代码。顺便说一下,我们也可以使用 broadcasting。
a[a .% 3 .!= 0]
这更类似于您在面向数组的语言(如 MATLAB 和 R)中看到的代码。
通过额外的 enumerate
调用,我们可以获得要操作的索引。
map((x) -> x[2], Iterators.filter(((x) -> x[1] % 3 != 0), enumerate(a)))
这大致就是您在 Python 中所做的。 enumerate
获取索引,filter
清除,然后 map
消除现在不需要的索引。
或者我们可以再次使用广播。
a[(1:length(a)) .% 3 .!= 0]
答案 1 :(得分:4)
如果您需要按索引跳过,最优雅的方法是使用 InvertedIndices
julia> using InvertedIndices # or using DataFrames
julia> a[Not(3:3:end)]
4-element Vector{Int64}:
1
2
4
5
正如您所看到的,您在这里的所有工作就是提供一系列您希望跳过的索引。
答案 2 :(得分:1)
如果你想按索引过滤,一种方便的方法是使用推导式:
julia> a = 10:10:100;
julia> [a[i] for i in eachindex(a) if i % 3 != 0] |> permutedims
1×7 Matrix{Int64}:
10 20 40 50 70 80 100
julia> vec(ans) == [a[1 + 3(j-1)÷2] for j in 1:7]
true
这隐含地涉及Iterators.filter
,并收集生成器。您也可以使用它来按值过滤,尽管急切的 filter
可能更有效:
julia> a = 1:10;
julia> [x for x in a if x%3!=0] |> permutedims
1×7 Matrix{Int64}:
1 2 4 5 7 8 10
也许对所有这些进行计时很有趣:
julia> using BenchmarkTools, InvertedIndices
julia> a = rand(1000); # filter by index
julia> i1 = @btime [$a[1 + 3(j-1)÷2] for j in 1:667];
373.162 ns (1 allocation: 5.38 KiB)
julia> i2 = @btime $a[eachindex($a) .% 3 .!= 0];
1.387 μs (4 allocations: 9.80 KiB)
julia> i3 = @btime [$a[i] for i in eachindex($a) if i % 3 != 0];
3.557 μs (11 allocations: 16.47 KiB)
julia> i4 = @btime map((x) -> x[2], Iterators.filter(((x) -> x[1] % 3 != 0), enumerate($a)));
4.202 μs (11 allocations: 16.47 KiB)
julia> i5 = @btime $a[Not(3:3:end)];
84.333 μs (4655 allocations: 182.28 KiB)
julia> i1 == i2 == i3 == i4 == i5
true
julia> a = rand(1:99, 1000); # filter by value
julia> v1 = @btime filter(x -> x%3!=0, $a);
532.185 ns (1 allocation: 7.94 KiB)
julia> v2 = @btime [x for x in $a if x%3!=0];
5.465 μs (11 allocations: 16.47 KiB)
julia> v1 == v2
true
答案 3 :(得分:0)
这应该对您有所帮助:
b = a[Bool[i %3 != 0 for i = 1:length(a)]]
答案 4 :(得分:-1)
a[a .% 2 .!= 0]
请找到带有代码的 link。