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

时间:2018-01-19 16:09:53

标签: for-loop julia

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

示例:

List1 = ["a", "b", "c"]
for letter in List1
   println(previous letter)
end

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

4 个答案:

答案 0 :(得分:6)

不要让简单的事情复杂化:

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

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

输出:

The previous letter of b is a
The previous letter of c is b

答案 1 :(得分:3)

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

using IterTools

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

给出:

prev = "a"
prev = "b"

next具有当前迭代的值(即"b""c"),循环跳过第一个值的迭代(没有prev)。< / p>

答案 2 :(得分:1)

您可以使用enumerate函数获取上一个索引,例如:

julia> list1 = ["a", "b", "c"]
3-element Array{String,1}:
 "a"
 "b"
 "c"

julia> enumerate(list1)
Enumerate{Array{String,1}}(["a", "b", "c"])

julia> collect(ans)
3-element Array{Tuple{Int64,String},1}:
 (1, "a")
 (2, "b")
 (3, "c")

julia> function prev(list::Vector{String})
           enumeration = enumerate(list)
           for (index, element) in enumeration
               if index == 1
                   continue
               else
                   println("The previous letter of $element is $(list[index - 1]).")
               end
           end
       end
prev (generic function with 1 method)

julia> prev(list1)
The previous letter of b is a.
The previous letter of c is b.

答案 3 :(得分:0)

我想我找到了一种自己做的方法:

List1 = ["a", "b", "c"]
for letter in List1
    if  !(findn(List1 .== letter) == [1])
        println("The previous letter of ", letter, " is ", List1[findn(List1 .== letter)-1])
    end
end

输出:

The previous letter of b is String["a"]
The previous letter of c is String["b"]

现在唯一的问题是结果是某种字符串数组。