给定一个数组:
arr = [1, 2, 3, 4, 5]
我想转移所有元素。
shift!(arr, 2) => [4, 5, 1, 2, 3]
在 Python 中,这是通过 Numpy 使用numpy.roll. 这是如何在 Julia 中完成的?
无需自己实现,有内置函数
julia> circshift(arr, 2)
5-element Array{Int64,1}:
4
5
1
2
3
Run Code Online (Sandbox Code Playgroud)
它也(稍微)比roll2上面提出的更有效:
julia> @btime circshift($arr, 2);
68.563 ns (1 allocation: 128 bytes)
julia> @btime roll2($arr, 2);
70.605 ns (4 allocations: 256 bytes)
Run Code Online (Sandbox Code Playgroud)
但是请注意,建议的功能都没有就地运行。他们都创建了一个新数组。还有circshift!(dest, src, shift)在预分配中运行的内置函数dest(但是,必须是!= src)。
| 归档时间: |
|
| 查看次数: |
1325 次 |
| 最近记录: |