执行函数和不执行函数的区别(Return 变量)

Difference of Execution in Function and Without Function (Return Variable)

所以我必须遵循代码以向测量数据添加一些偏移量。

这按计划进行:

IndexMax = [3, 10, 20, 30]
IndexMax2 = [3, 10, 20, 30] #Just for Computing purposes


for x in range(0, len(IndexMax)):
  if x == 0:
      IndexMax2[0] = 0; #First Data has no Offset per Definition
  elif len(IndexMax2) >= 1: #The 
      IndexMax2[x] = IndexMax[x-1] + IndexMax2[x-1]
      tmp = IndexMax2


print('Offsets are ' + str(tmp))

给出正确的输出:

Offsets are [0, 3, 13, 33]

但是不起作用的与以 Indexmax 作为参数的函数相同:

def Offsetcalcalculater(IndexMax):
     IndexMax = IndexMax
     IndexMax2 = IndexMax


     for x in range(0, len(IndexMax)):
         if x == 0:
              IndexMax2[0] = 0; #First Data has no Offset per Definition
         elif len(IndexMax2) >= 1: #The 
              IndexMax2[x] = IndexMax[x-1] + IndexMax2[x-1]
              tmp = IndexMax2
     return IndexMax2

调用它
IndexMaxtest = [3, 10, 20, 30]
IndexMax2 = Offsetcalcalculater(IndexMaxtest)

导致:

IndexMax2 [0, 0, 0, 0]

为什么函数的行为与上面的代码不同?

您正在对 IndexMax 进行浅拷贝 IndexMaxIndexMax2 都引用相同的列表

IndexMax    Indexmax2
#    |            |
#    |            |
#     \          /  
#      \        /
#       IndexMax  

要解决此问题,请使用 .copy 复制列表。

def Offsetcalcalculater(IndexMax):
     IndexMax = IndexMax
     IndexMax2 = IndexMax.copy() #---->


     for x in range(0, len(IndexMax)):
         if x == 0:
              IndexMax2[0] = 0; #First Data has no Offset per Definition
         elif len(IndexMax2) >= 1: #The 
              IndexMax2[x] = IndexMax[x-1] + IndexMax2[x-1]
              tmp = IndexMax2
     return IndexMax2
IndexMax = [3, 10, 20, 30]
IndexMax2 = [3, 10, 20, 30]

是对两个不同列表的两个引用。改了一个,第二个就不会改了。

 IndexMax = IndexMax
 IndexMax2 = IndexMax

另一方面,是对同一个列表的两个引用。更改 IndexMax 中的某些内容将导致 IndexMax2

中的相同更改