在for循环期间执行进程同时为true

时间:2017-03-01 15:00:04

标签: python loops for-loop while-loop do-while

我的代码基本上就是这样

P = matrix # initialise value of P matrix
x = some other matrix

for i, val in enumerate(vals):

    lots of matrix calculations involving P and x

    y = z - j # this is the important line

    lots of matrix calculations UPDATING P and x

    return values of P and x for each step

现在我想改变我的代码,这样如果y大于某个阈值,比如y> 0.5,我将P和x重置为它们的初始值 - 并再次继续循环,就像它刚刚从头开始一样。我不确定最好的方法,我是python的新手所以任何特定的帮助都会非常有用 - 我不确定我是否应该在for循环中使用另一个循环 - 或者定义我的计算在一个功能。

干杯

取值

1 个答案:

答案 0 :(得分:1)

在python list中是一个可变对象。要在计算中间从头开始,保持原始列表的深度复制并使用原始值重新分配P和x并继续。像这样:

import copy
P = matrix # initialise value of P matrix
x = some other matrix
p1= copy.deepcopy(P)
x1= copy.deepcopy(x)
for i, val in enumerate(vals):
  lots of matrix calculations involving P and x
  y = z - j # this is the important line
  if y > threshold:
    P = p1
    x = x1
    continue
  lots of matrix calculations UPDATING P and x
  return values of P and x for each step