arrays - 循环迭代器并改变大小和值

标签 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

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


编辑

让我尝试用一​​行总结它:我希望能够循环遍历 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/

相关文章:

c - 将字符串存储在 char 数组中

c++ - 为什么要指向数组或 vector 中最后一个元素之后的内存位置?

PHP XML 到具有属性和值的数组/对象

java - 找不到支持运行固定数量的步骤然后暂停的语言(-解释器)

julia - 在 DifferentialEquations.jl 中的 n 次回调后,是否有一种惯用的方法来终止积分

java - 如何以不同的方法从数组列表中选择大小写

c++ - 如果基类包含数组成员,则派生类的构造函数不能是 constexpr

task - Julia:在协程(任务)之间传递数据

arrays - Julia 中的手动类型推断

performance - Julia 中的并行实现比串行慢