Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么价值观发生了变化?_Python_Python 3.x_List_Jupyter Notebook - Fatal编程技术网

Python 为什么价值观发生了变化?

Python 为什么价值观发生了变化?,python,python-3.x,list,jupyter-notebook,Python,Python 3.x,List,Jupyter Notebook,函数二 def func_two(x): x[1][1] = x[2][1] x[2][1] = 0 return x a = [[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]] print(a, ":before function") b = func_two(a) print(a, ":after function") print(b, ":

函数二

def func_two(x):
    x[1][1] = x[2][1]
    x[2][1] = 0 
    return x

a = [[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]]
print(a, ":before function")
b = func_two(a)
print(a, ":after function")
print(b, ":value of b")
这方面的输出是

[[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]] :before function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :after function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :value of b
[[5]] :before function
[[5]] :after function
[[3]] :value of b
为什么函数之后“a”的值会发生变化? 如何在不更改函数外部变量的情况下运行func_two(我没有将任何变量声明为全局变量,这不应该发生)

能够正常工作的代码

def func_one(x):
    x = [[3]]
    return x 

a = [[5]]
print(a, ":before function")

b = func_one(a)

print(a, ":after function")
print(b, ":value of b")
这方面的输出是

[[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]] :before function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :after function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :value of b
[[5]] :before function
[[5]] :after function
[[3]] :value of b

当func\u 2不工作时,为什么func\u 1工作?

这个问题已经在@user2357112和@Wups的评论中得到了回答

答复

import copy

def transition(x):
    y = copy.deepcopy(x)
    y[1][1] = y[2][1]
    y[2][1] = 0 
    return y

a = [[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]]

print(a, ":before function")

b = transition(a)

print(a, ":after function")

您期望的隐式副本比Python多得多。我推荐阅读-这是一篇关于Python变量和对象如何工作的很好的介绍。谢谢,@Wups确实解决了我的问题。谢谢@Monica,--nedbatcheld.com/text/names.html--这是一篇很好的阅读,我不知道Python是如何处理变量的。这实际上解释了我以前犯过的很多错误(我以前是通过上帝知道如何解决的(做随机的事情)),不知道问题发生的真正原因!!!!谢谢