Julia - Accessing two elements in a for loop

What is a quick way to get two neighboring elements when going through a for loop in julia?

Let's pretend that

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

Is there any way to get both elements iand the next i+1?

+4
source share
3 answers

Yes it is possible. Since this is a common occurrence, a special tester has been identified in Iterators.jljust for this kind of task. Other special iterators are also very useful (from personal experience) and are worth exploring.

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

The 2,1of parameters partitionare the size and step of the tuples.

+10
source

Refer to Julia Doc , The General Cycle forin Julia:

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
< =#
+3

I really like 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

The idea is for the function to leave a second value so that it can be used as the first value of the next pair.

You can go back if you use foldr()and return the first value:

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
+2
source

Source: https://habr.com/ru/post/1620558/


All Articles