最好通过示例来解释这一点。我想做这样的事情:
tstops = [20;40]
for i in eachindex(tstops)
if tstops[i] == 20
push!(tstops,70)
end
if tstops[i] == 40
push!(tstops,60)
end
if tstops[i] == 70
tstops[end] = 100
end
@show tstops[i]
end
但实际上显示 20、40、60、70、100(按顺序)。此设置的问题在于 eachindex(tstops)
是 Base.OneTo{2}
,因此它仅打印 20,然后打印 40,而不会动态更改。如果我直接使用迭代器:
tstops = [20;40]
for t in tstops
if t == 20
push!(tstops,70)
end
if t == 40
push!(tstops,60)
end
if t == 70
tstops[end] = 100
end
@show tstops
@show t
end
输出:
tstops = [20,40,70]
t = 20
tstops = [20,40,70,60]
t = 40
tstops = [20,40,70,100]
t = 70
tstops = [20,40,70,100]
t = 100
所以我需要一种快速的方法来对其进行排序才能使其正常工作。然而,即使它被排序,最后的突变也不会使其同时达到 70 和 100,而只是 70:
tstops = [20;40]
for t in tstops
if t == 20
push!(tstops,60)
end
if t == 40
push!(tstops,70)
end
if t == 70
tstops[end] = 100
end
@show tstops
@show t
end
请注意,实现也应该尝试获得尽可能好的性能。是否有一个好的数据结构来处理这个问题,包括排序和“改变当前点”?
编辑
让我尝试用一行总结它:我希望能够循环遍历 tstops
中的 t
并命中 tstops
的每个值> 按顺序,但是(困难的部分)我希望能够动态更改 tstops
。
最佳答案
我不清楚所需的确切行为,但也许这可以:
using Base.Collections
tstops = [20,40]
heapify!(tstops)
while !isempty(tstops)
t = heappop!(tstops)
if t == 20
heappush!(tstops,70)
end
if t == 40
heappush!(tstops,60)
end
if t == 70
heappush!(tstops,100)
end
@show tstops
@show t
end
结果是:
tstops = [40,70]
t = 20
tstops = [60,70]
t = 40
tstops = [70]
t = 60
tstops = [100]
t = 70
tstops = Int64[]
t = 100
关于arrays - 循环迭代器并改变大小和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41253936/