理解 Python 变量赋值 [英] Understanding Python variables assignment

查看:33
本文介绍了理解 Python 变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我执行此代码:

a = [1,2,3]b = ab.移除(2)打印(a,b)

我希望看到的是:

[1,2,3] [1,3]

但这就是我真正得到的:

[1,3] [1,3]

为什么调用 b.remove(2) 也会影响 a?如果我想更改b,同时在a 中保留原始内容的副本怎么办?

解决方案

当您执行 b = a 时,您只需创建对同一列表的另一个引用.所以对该列表的任何修改都会影响ab.因此,执行 b.remove(2) 会影响您拥有的单个列表.

如果您想获得预期的结果,可以创建列表的副本:

b = a[:]

通过这种方式,您可以创建列表的副本,并且可以修改其中一个而不更改另一个.

<预><代码>>>>a = [1,2,3]>>>b = a[:]>>>b.移除(2)>>>打印 a,b[1, 2, 3] [1, 3]

If I execute this code:

a = [1,2,3]
b = a
b.remove(2)
print(a,b)

What I expect to see is:

[1,2,3] [1,3]

But this is what I really get:

[1,3] [1,3]

Why calling b.remove(2) also affects a? What if I want to change b,while keeping a copy of the original content in a?

解决方案

When you do b = a, you simply create another reference to the same list. So any modifications to that list will affect both a and b. So doing b.remove(2) will affect the single list that you have.

If you want to get your expected results, you can create a copy of the list:

b = a[:]

This way, you create a copy of the list, and you can modify one without changing the other.

>>> a = [1,2,3]
>>> b = a[:]
>>> b.remove(2)
>>> print a,b
[1, 2, 3] [1, 3]

这篇关于理解 Python 变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆