我想用一个简单的条件对向量进行子集,并将结果保留在初始向量中:
x = [1,2,3,4,5]
y = 4
x = x[x .< 4]1 2 3
它运行得很好,但是如果我有较长的变量名,则如下所示:
position = position[position .< 4]有没有其他更优雅的方法来做到这一点,而不键入相同的变量名称3次在朱莉娅。
发布于 2022-06-07 22:30:53
julia> x = [1,2,3,4,5];
julia> filter!(<(4), x)
3-element Vector{Int64}:
1
2
3这样可以进行就地筛选,如果您想要复制,则使用filter(<(4), x)代替。
请注意,在这种情况下,filter!函数是筛选向量的最快方法。
julia> x = [1,2,3,4,5]
julia> @btime filter!(<(4), $x)
5.500 ns (0 allocations: 0 bytes)
julia> x = [1,2,3,4,5]
julia> @btime $x = $x[$x .< 4];
94.618 ns (3 allocations: 176 bytes)https://stackoverflow.com/questions/72537775
复制相似问题