交换变量?

时间:2015-12-28 14:18:10

标签: python

我正在做如何像计算机科学家一样思考的练习,我无法得到第11章第11号练习的答案。

我应该找到为什么这段代码无效。

def swap(x,y):
    print("before swap statement: x:", x, "y:", y)
    (x,y) = (y,x)
    print("after swap statement: x:", x, "y:", y)

a = ["This", "is", "fun"]
b = [2,3,4]
print ("before swap function call: a:", a, "b:", b)
swap(a,b)
print("after swap function call: a:", a, "b:",b)

此代码的结果是

('before swap function call: a:', ['This', 'is', 'fun'], 'b:', [2, 3, 4])
('before swap statement: x:', ['This', 'is', 'fun'], 'y:', [2, 3, 4])
('after swap statement: x:', [2, 3, 4], 'y:', ['This', 'is', 'fun'])
('after swap function call: a:', ['This', 'is', 'fun'], 'b:', [2, 3, 4])

交换(a,b)取a,b和do(a,b)=(b,a),所以我很好奇为什么这不起作用。有人可以给我一个解释或答案吗?

0 个答案:

没有答案