Python 3.5.4rc1,Deepin 64 位系统。刚学 python,遇到一个奇怪的 bug,不知道是我的问题还是解释器的问题,代码如下。
L1=[1,2,1]
L2=[1,2,1]
#L2=L1
for i in range (1,3):
L1[i]=L2[i]+L2[i-1]
print (L1)
这样执行的是预期的结果,但如果去掉第三行的注释,并把第二行注释掉,得到的结果就无法理解了。 理论上这两种写法不是等价的吗?
1
kindjeff 2018-02-11 20:03:06 +08:00 1
关键字:『 Python 不可变对象』
|
2
TuringGunner 2018-02-11 20:03:55 +08:00 via iPhone
不一样啊,你现在是两个单独的对象
第三行的写法,实际指向的是同一个,也就是说你改了 L1,L2 也会跟着变 |
3
wellsc 2018-02-11 20:04:58 +08:00
日经
|
4
rabbbit 2018-02-11 20:05:38 +08:00
L1=[1,2,1]
L2=L1 L2[0] = 3 print L1 // [3, 2, 1] |
5
lmqdlr 2018-02-11 20:13:15 +08:00 via Android
当然不一样,引用类型,值类型了解一下
|
6
LokiSharp 2018-02-11 20:15:27 +08:00
'''
def a(): L1 = [1, 2, 1] L2 = [1, 2, 1] # L2=L1 for i in range(1, 3): L1[i] = L2[i] + L2[i - 1] print(L1) def b(): L1 = [1, 2, 1] L2 = [1, 2, 1] L2 = L1 for i in range(1, 3): L1[i] = L2[i] + L2[i - 1] print(L1) from dis import dis dis(a) print("==================================================") dis(b) 2 0 LOAD_CONST 1 (1) 2 LOAD_CONST 2 (2) 4 LOAD_CONST 1 (1) 6 BUILD_LIST 3 8 STORE_FAST 0 (L1) 3 10 LOAD_CONST 1 (1) 12 LOAD_CONST 2 (2) 14 LOAD_CONST 1 (1) 16 BUILD_LIST 3 18 STORE_FAST 1 (L2) 5 20 SETUP_LOOP 42 (to 64) 22 LOAD_GLOBAL 0 (range) 24 LOAD_CONST 1 (1) 26 LOAD_CONST 3 (3) 28 CALL_FUNCTION 2 30 GET_ITER >> 32 FOR_ITER 28 (to 62) 34 STORE_FAST 2 (i) 6 36 LOAD_FAST 1 (L2) 38 LOAD_FAST 2 (i) 40 BINARY_SUBSCR 42 LOAD_FAST 1 (L2) 44 LOAD_FAST 2 (i) 46 LOAD_CONST 1 (1) 48 BINARY_SUBTRACT 50 BINARY_SUBSCR 52 BINARY_ADD 54 LOAD_FAST 0 (L1) 56 LOAD_FAST 2 (i) 58 STORE_SUBSCR 60 JUMP_ABSOLUTE 32 >> 62 POP_BLOCK 7 >> 64 LOAD_GLOBAL 1 (print) 66 LOAD_FAST 0 (L1) 68 CALL_FUNCTION 1 70 POP_TOP 72 LOAD_CONST 0 (None) 74 RETURN_VALUE ================================================== 11 0 LOAD_CONST 1 (1) 2 LOAD_CONST 2 (2) 4 LOAD_CONST 1 (1) 6 BUILD_LIST 3 8 STORE_FAST 0 (L1) 12 10 LOAD_CONST 1 (1) 12 LOAD_CONST 2 (2) 14 LOAD_CONST 1 (1) 16 BUILD_LIST 3 18 STORE_FAST 1 (L2) 13 20 LOAD_FAST 0 (L1) 22 STORE_FAST 1 (L2) 14 24 SETUP_LOOP 42 (to 68) 26 LOAD_GLOBAL 0 (range) 28 LOAD_CONST 1 (1) 30 LOAD_CONST 3 (3) 32 CALL_FUNCTION 2 34 GET_ITER >> 36 FOR_ITER 28 (to 66) 38 STORE_FAST 2 (i) 15 40 LOAD_FAST 1 (L2) 42 LOAD_FAST 2 (i) 44 BINARY_SUBSCR 46 LOAD_FAST 1 (L2) 48 LOAD_FAST 2 (i) 50 LOAD_CONST 1 (1) 52 BINARY_SUBTRACT 54 BINARY_SUBSCR 56 BINARY_ADD 58 LOAD_FAST 0 (L1) 60 LOAD_FAST 2 (i) 62 STORE_SUBSCR 64 JUMP_ABSOLUTE 36 >> 66 POP_BLOCK 16 >> 68 LOAD_GLOBAL 1 (print) 70 LOAD_FAST 0 (L1) 72 CALL_FUNCTION 1 74 POP_TOP 76 LOAD_CONST 0 (None) 78 RETURN_VALUE ''' |
7
juoyi 2018-02-11 20:20:05 +08:00
注释打开后,两个变量指向同一片内存地址
|