简体   繁体   English

Python输出说明

[英]Explanation for output in Python

I came across a piece of python code, requiring me to give the output. 我遇到了一段python代码,要求我提供输出。 The code goes as follows: 代码如下:

a = [1, 2]
b = [a, 3]
c = b[:]
a[0] = 7
b[1] = 8
print c

I thought the output to be [[7, 2], 8] since i have the reference to the a in b , and consequently, c had the reference to b 我认为输出为[[7, 2], 8]因为我在b引用a b ,因此c引用了b

But the output came out to be [[7, 2], 3] 但是输出结果是[[7, 2], 3]

What am I missing here? 我在这里想念什么?

c had the reference to b c引用了b

This is where you went wrong. 这是您出问题的地方。 c is initialized as a (shallow) copy of b . c初始化为b的(浅)副本。

If it were simply c = b (without the [:] ) then you'd be correct. 如果只是c = b (不带[:] ),那么您将是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM