python中的函数改变了输入变量,为什么会这样?

时间:2015-11-14 10:51:23

标签: python python-2.7

此代码:

def do_something(arg):
    x=arg
    x[0] = 9
    return x

y = [1,2]

print "before: ", y
print "result of do_something(): ", do_something(y)
print "after: ", y

结果如下:

before:  [1, 2]
result of do_something():  [9, 2]
after:  [9, 2]

我不知道为什么函数会改变我传递的原始列表? 我甚至(尝试)创建一个新的arg(x)副本来防止它。 即使我不返回x,我仍然得到相同的结果。

4 个答案:

答案 0 :(得分:1)

Python语言中的所有参数(参数)都通过引用传递。因此,您将引用传递给列表对象。在功能中,您可以在列表中进行更改。所以,这就是你在调用函数后看到更改列表的原因。

要避免 - 复制列表/创建一个新列表,使用它并作为该函数的结果返回它。

答案 1 :(得分:1)

因为list作为链接传递给原始对象。您需要在函数中复制它或将其传递给列表中的新对象 你可以这样做:

def do_something(arg):
    x=arg[:]
    x[0] = 9
    return x

y = [1,2]

print "before: ", y
print "result of do_something(): ", do_something(y)
print "after: ", y

结果:

before:  [1, 2]
result of do_something():  [9, 2]
after:  [1, 2]

答案 2 :(得分:1)

y = [1,2]

y ----> [1, 2]
def do_something(arg):
                  ^
                  |
     do_something(y) causes python to do this assignment: arg = y


y ----> [1, 2]
          ^
          |
arg ------+
x = arg 

    y ---->  [1, 2]
              ^  ^
              |  |
    arg ------+  |
                 |      
    x -----------+

然后,使用xarg更改列表将导致y看到的列表发生变化。换句话说,所有变量都引用相同的列表。

  

我甚至(尝试)创建一个新的arg(x)副本来防止它。即使我   不要返回x,我仍然得到相同的结果。

不正确:

def do_something(arg):
    x = arg[:]
    x[0] = 9
    return x

y = [1,2]
result = do_something(y)
print y
print result

--output:--
[1, 2]
[9, 2]

答案 3 :(得分:1)

  

Everything is a reference in Python. If you wish to avoid that behavior you would have to create a new copy of the original with list(). If the list contains more references, you'd need to use deepcopy()

如果您打印21.010574093274126let thisStep: MKRouteStep = (self.carRoute?.steps[self.stepsCounter])! let pointsArray = thisStep.polyline.points() let lastPoint = pointsArray[thisStep.polyline.pointCount - 1] let theLoc: CLLocationCoordinate2D = MKCoordinateForMapPoint(lastPoint) self.theRegion = CLCircularRegion(center: theLoc, radius: 50, identifier: "turningPoint") 的地址,您会发现他们的地址相同,从而导致结果。

x