简体   繁体   English

Python 3 比较列表变量

[英]Python 3 comparing list variables

I want to make list b equal to list a , and then change b without influencing a.我想让 list b等于 list a ,然后在不影响 a 的情况下更改b

a = "1234"
b = ""
a = list(a)
b = a

When I print(a) after changing b , a changes as well.当我在更改bprint(a)时, a也会发生变化。 Although in the code below, I don't get this problem, meaning whatever change I make to variable b , a will stay independent.尽管在下面的代码中,我没有遇到这个问题,这意味着我对变量b所做的任何更改, a都将保持独立。

a = "1234"
b = ""
a = list(a)
b = list(a)

I am looking for an explanation on what happened behind the scenes and why the second code example worked.我正在寻找有关幕后发生的事情以及第二个代码示例为何起作用的解释。

When you assign b=a , Python assigns by reference, so the variable b is just pointing to the same object as a .当您分配b=a时, Python 通过引用分配,因此变量b只是指向与a相同的 object 。 You can confirm this with the id() method that prints out the ID of the object:您可以使用打印出 object 的 ID 的id()方法来确认这一点:

>>> a="1234"
>>> id(a)
2858676454064
>>> b=a
>>> id(b)
2858676454064

When you do b = list(a) , the list() method returns a new list.当您执行b = list(a)时, list()方法会返回一个新列表。

>>> a = list(a)
>>> id(a)
2858676458880
>>> b = list(a)
>>> id(b)
2858676458944

After a = list(a) , the a object is no longer the same as the a previously (2858676454064).a = list(a)之后, a object 不再与之前的a (2858676454064) 相同。

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

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