【问题标题】:How to keep variables fixed within a while loop [duplicate]如何在while循环中保持变量固定[重复]
【发布时间】:2021-10-19 17:50:54
【问题描述】:

我有两个变量(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 循环运行了一次迭代,并且在此迭代结束时 switch 仍然为 True,则 variable_1variable_2 不会设置回其原始值。我怎样才能做到这一点? (请记住,我不想为之前或之后的整个代码修复 variable_1variable_2)。

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

编辑:如果我对变量进行硬编码(意味着我在内部函数上方编写 variable_1 = "its value" 和 variable_2 = "its value",它可以工作。但我不想这样做。

【问题讨论】:

  • 您是说inner_function 是在function() 内部定义的,因此可以访问variable_1variable_2 以便能够更改它们?
  • 认真的吗?将它们存储在其他变量中并在循环开始时重置
  • @qamrana 没有,里面没有定义,只是调用而已。
  • 这不是实际代码。您应该提供一个展示您所面临问题的真实代码的最小示例。
  • 在将列表传递给函数时对其进行深层复制。

标签: python variables while-loop fixed


【解决方案1】:

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

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.~

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2013-10-29
      • 2016-01-12
      • 2014-12-07
      • 2021-05-31
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多