有没有办法在Julia的for循环中使用前一个和后一个值?我在Julia文档中没有找到任何答案。
例如:
例如:
List1 = ["a", "b", "c"]
for letter in List1
println(previous letter)
end
当这个循环作用于“b”时,它将给出“a”作为结果,等等。
另一种方法是使用IterTools.jl包中的partition
迭代器:
using IterTools
List1 = ["a", "b", "c"];
for (prev,next) in partition(List1,2,1)
@show prev
end
提供:
prev = "a"
prev = "b"
< p > next
的值为当前的迭代值(即"b"
和"c"
"),循环将跳过第一个值(没有prev
)。
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
for i = firstindex(List1)+1:lastindex(List1)
进行自定义索引,这不应该丢失任何元素。 - AboAmmarenumerate
函数来获取前一个索引,类似这样: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.
我想我找到了一种自己实现的方法:
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"]
现在唯一的问题是结果是某种字符串数组。