Reassigning variables in python
本问题已经有最佳答案,请猛点这里访问。
我有以下代码和变量,我想找出代码执行后的变量
1 2 3 4 5 6 7 8 9 10 11 12 | def do_something(a, b): a.insert(0,"z") b = ["z"] + b a = ["a","b","c"] a1 = a a2 = a[:] b = ["a","b","c"] b1 = b b2 = b[:] do_something(a, b) |
我尝试的解决方案如下:
1 2 3 4 5 6 | a = ["z","a","b","c"] a1 = ["a","b","c"] a2 = ["a","b","c"] b = ["z""a","b","c"] b1 = ["a","b","c"] b2 = ["a","b","c"] |
但实际的解决方案是:
1 2 3 4 5 6 | a = ["z","a","b","c"] a1 = ["z","a","b","c"] a2 = ["a","b","c"] b = ["a","b","c"] b1 = ["a","b","c"] b2 = ["a","b","c"] |
有人能带我度过我的错误吗?
好的,您可以将Python中的变量视为引用。当你这样做的时候:
1 | a1 = a |
但当你这样做的时候:
1 | a2 = a[:] |
那么,
列表的
1 | b = ['z'] + b |
您将为
但是作用域可能更复杂:您可以从函数中看到封闭作用域,但是如果在函数中分配一个变量,它不会在封闭(或全局或内置)作用域中更改同名的变量,而是在本地作用域中创建一个同名的变量。这就是为什么b没有被改变的原因——好吧,不是很好,在python中传递参数是一个赋值操作,所以当有一个名为
1 2 3 4 5 | def do_something(a, b): a.insert(0,"z") # mutates a in-place return ["z"] + b b = do_something(a, b) |