python - a=[1,2,3,4,5],b=a和b=a[:],有区别么?
ringa_lee
ringa_lee 2017-04-18 09:23:15
0
3
1018
ringa_lee
ringa_lee

ringa_lee

reply all(3)
迷茫

You call it

b.append(6)
print (a, b)

You can see the difference:

  • The former passes the reference

  • The latter is a copy

大家讲道理
  • b=a 會讓 b 參考到 a Reference object

  • a[:] 會製造一個 a 的副本, 所以 b=a[:] 會讓 b 參考到這個副本, 也就是說 ba Now refer to different objects, but these two objects are equal ( not the same but equivalent )

This is why on the surface there seems to be no difference between the two, but if it is the former, we have changed ba Both will be affected because they refer to the same object, but the latter does not affect each other because they refer to different objects. . @hsfzxjy's example is to point this out, and you can learn the difference by doing experiments.


Questions I answered: Python-QA

Ty80

Python has a function called id that can get the address of an object. It will be clear if you print it out. Direct = is reference assignment, referencing the original object; and [:] is re-derivation, which will generate a new object

a=[1,2,3,4,5]
b=a
c=a[:]
print id(a),id(b),id(c)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template