Julia - for循环中的上一个和下一个值

mai*_*apo 3 for-loop julia

有没有办法在Julia中使用for循环中的previous和next值进行操作?我无法从Julia文档中找到任何答案.

例:

List1 = ["a", "b", "c"]
for letter in List1
   println(previous letter)
end
Run Code Online (Sandbox Code Playgroud)

当它在"b"上运行时,这个循环会给出"a"等等.

Abo*_*mar 6

没有简单的事情复杂化:

List1 = ["a", "b", "c"]

for i = 2:length(List1)
    println("The previous letter of $(List1[i]) is $(List1[i-1])")
end 
Run Code Online (Sandbox Code Playgroud)

输出:

The previous letter of b is a
The previous letter of c is b
Run Code Online (Sandbox Code Playgroud)


Dan*_*etz 5

另一种方法是使用partitionIterTools.jl 包中的迭代器:

using IterTools

List1 = ["a", "b", "c"];
for (prev,next) in partition(List1,2,1)
    @show prev
end
Run Code Online (Sandbox Code Playgroud)

给出:

prev = "a"
prev = "b"
Run Code Online (Sandbox Code Playgroud)

next具有当前迭代的值(即"b""c")并且循环跳过第一个值的迭代(没有prev)。