循环遍历迭代器,改变大小和值

时间:2016-12-21 01:52:28

标签: arrays julia

最好通过示例解释。我想做点什么:

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

请注意,实现应尽量获得尽可能高的性能。是否有一个很好的数据结构来处理这个问题,包括排序和“改变当前点”?

修改

让我尝试在一行中总结一下:我希望能够在t中循环tstops并按顺序点击tstops的每个值,但是(难点) )我希望能够动态更改tstops

1 个答案:

答案 0 :(得分:3)

我不清楚所需的确切行为,但也许这样做:

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