Python 在for循环期间执行进程而为true
我的代码基本上是这样的Python 在for循环期间执行进程而为true,python,loops,for-loop,while-loop,do-while,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
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循环中使用另一个循环——或者在函数中定义我的计算
干杯
在python
列表中,S是一个可变对象。若要在计算过程中从头开始,请维护原始列表的深度副本,并使用原始值重新分配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
我正在使用numpy数组,这种方法仍然有效吗?是的,它会。copy.deepcopy:深度副本构造一个新的复合对象,然后递归地将在原始副本中找到的对象的副本插入其中。很酷,只是想实现这个。它在我的例子中不起作用-我不完全清楚为什么,但它继续使每个P和x值P1和x1?我不知道你是否可以用这些小信息来调试它,但可能会回复你