python 引用传值、赋值

python 数组 A=B 默认的是引用传值,改变A中的元素,B中的元素同样改变。
而A=B[:]则是传值,改变A中的元素的值,B中元素的值保持不变。
具体传值和引用可以参考https://www.cnblogs.com/shizhengwen/p/6972183.html
样例:
引用

a=[1,2,3,4]
b=a[:]
b[0]=4
print(b)
print(a)


def Cal(A):
    B=[]
    B=A
    B[0]=4
    return B
a=[[1,2,3,4]]
b=Cal(a)
#b[0]=4
print(b)
print(a)

输出:
[4, 2, 3, 4]
[1, 2, 3, 4]
[4]
[4]

a=[1,2,3,4]
b=a
b[0]=4
print(b)
print(a)

输出:
[4, 2, 3, 4]
[4, 2, 3, 4]

猜你喜欢

转载自blog.csdn.net/th_num/article/details/80336500