如何在while循环中保持变量固定



我有两个变量(variable_1variable_2)。它们是一个算法的输出,它们总是不同的,因为算法包含一些随机的部分。

然后我有一个很长很复杂的函数,它把这些变量作为输入。其基本结构为:

def function(variable_1, variable_2):
switch = True
while switch:
variable_1
variable_2
inner_function(variable_1, variable_2):
~changes variable_1 and variable_2 randomly~
~changed variable_1 and variable_2 are then transformed with data structure comprehensions.~
~in the end, there is a condition. If variable_1 and variable_2 meet this condition, switch is turned to False and the function ends. If not, the while loop shall start again, but with the original values of variable_1 and variable_2.~

函数的目的是输出更改后的变量。问题是,它不起作用。如果while循环运行一次迭代,并且在该迭代结束时开关仍然为True,则variable_1variable_2不会被设置回其原始值。我该怎么做呢?(请记住,我不想为之前或之后的整个代码修复variable_1variable_2)。

很抱歉没有给出一个最低限度可复制的例子。考虑到这个函数的长度和复杂性,我想不出一个。

编辑:如果我硬编码变量(意思是我写variable_1 = "它的值"variable_2 =其值"在内部函数之上,它可以工作。但是我不想这样做。

所以你只需要创建一个deepcopy:

import copy
def function(variable_1o, variable_2o):
switch = True
while switch:
variable_1 = copy.deepcopy(variable_1o)
variable_2 = copy.deepcopy(variable_2o)
inner_function(variable_1, variable_2)

这里你实际上是在问:"如何通过值而不是通过引用传递变量"。其中一种方法是将原始变量放入列表,然后从该列表创建另一个列表,然后将第二个列表作为参数传递给函数。这将模仿按值传递变量,而不是按引用。
像这样:

def function(variable_1, variable_2):
original_list = [variable_1, variable_2]
switch = True
while switch:
copy_list = original_list[:]      
inner_function(copy_list):
#here you can use, change etc the data in copy_list safely
~changes variable_1 and variable_2 randomly~
~changed variable_1 and variable_2 are then transformed with data structure comprehensions.~
~in the end, there is a condition. If variable_1 and variable_2 meet this condition, switch is turned to False and the function ends. If not, the while loop shall start again, but with the original values of variable_1 and variable_2.~

最新更新