Julia - 访问for循环中的两个元素

时间:2015-12-17 13:54:43

标签: julia

julia中循环for循环时,获取两个相邻元素的快捷方法是什么?

假设我有

z = linspace(1, 10, 9)
for i in z[1:length(z)-1]
    println(i, " ")
end

我可以以某种方式获得元素i和下一个元素i+1吗?

3 个答案:

答案 0 :(得分:9)

是的,这是可能的。由于它很常见,因此在Iterators.jl中已经为这种任务定义了一个特殊的迭代器。其他特殊的迭代器也非常有用(来自个人经验),值得研究。

using Iterators # may have to Pkg.add("Iterators") first

z = linspace(1,10,9)
for (v1,v2) in partition(z,2,1)
    @show v1,v2
end

2,1的参数partition是元组的大小和步骤。

答案 1 :(得分:3)

请参阅朱莉娅Doc,朱莉娅的一般for循环:

for i = I   # or  "for i in I"
    # body
end

被翻译成while结构:

state = start(I)
while !done(I, state)
    (i, state) = next(I, state)
    # body
end

因此,使用相同的语法,可以简单地实现自定义&有效的循环,例如下一个在每次迭代中提取两个相邻元素:

I=linspace(1, 10, 9)
state = start(I)
while !done(I, state)
  (i, state) = next(I, state) # 
  (j, _)     = next(I, state) # extract next element without update state
  println(i,' ',j)
end
#= >
1.0 2.125
2.125 3.25
3.25 4.375
4.375 5.5
5.5 6.625
6.625 7.75
7.75 8.875
8.875 10.0
10.0 11.125
< =#

答案 2 :(得分:2)

我非常喜欢reduce()

julia> z = linspace(1, 10, 10);
julia> reduce((x, y) -> (println("$x + $y = $(x+y)"); y), z)
1.0 + 2.0 = 3.0
2.0 + 3.0 = 5.0
3.0 + 4.0 = 7.0
4.0 + 5.0 = 9.0
5.0 + 6.0 = 11.0
6.0 + 7.0 = 13.0
7.0 + 8.0 = 15.0
8.0 + 9.0 = 17.0
9.0 + 10.0 = 19.0
10.0

这个想法是让函数留下第二个值,以便它可以用作下一个值的第一个值。

如果您使用foldr()并返回第一个值,则可以向后退:

julia> foldr((x, y) -> (println("$x + $y = $(x+y)"); x), z)
9.0 + 10.0 = 19.0
8.0 + 9.0 = 17.0
7.0 + 8.0 = 15.0
6.0 + 7.0 = 13.0
5.0 + 6.0 = 11.0
4.0 + 5.0 = 9.0
3.0 + 4.0 = 7.0
2.0 + 3.0 = 5.0
1.0 + 2.0 = 3.0
1.0
相关问题