X = Y =列表与数字 [英] X = Y = Lists vs Numbers

查看:50
本文介绍了X = Y =列表与数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中:修改值时,我有2条代码表现不同:

In python : I have 2 pieces of code behaving different when I modify values:

X = Y =数字

x = y = 2
x = 3

print(x)
print(y)

Output:
3
2

X = Y = [列表]

X = Y = [List]

x = y = ['a','b']
x[0] = 'd'

print(x)
print(y)

Output:
['d', 'b']
['d', 'b']

如果X更改了,为什么列表不尊重变量Y的原始值?

推荐答案

这两种情况比看起来的要大得多,并不是因为所涉及的类型.

These two cases are more different than they seem, and it isn't because of the types involved.

x = 3

这将更改 x 所查看的值.使用 = 重新分配 x 不会更改3..无论右侧是int还是列表,都没有关系.右侧的变量将被放置在左侧的变量中.

This changes what value x is looking at. Reassigning x using = does not change the 3. It wouldn't matter if the right hand side were a int, or a list. Whatever is on the right is put into the variable on the left.

x[0] = 'd'

这看起来相同,但实际上却大不相同.而不是简单的重新分配,这实际上是在内部转换为

This looks the same, but it's actually quite different. Instead of a simple reassignment, this is actually internally translated to

x.__setitem__(0, 'd')

这不仅仅是一个重新分配,它实际上是一个变种操作,它更改了对象 x 持有的.

Instead of being just a reassignment, this is actually a mutative operation that changes the object x is holding.

所以后者的行为有所不同的原因是,不是更改 x 持有的对象,而是更改 x 持有的对象本身.

So the reason the latter acts differently is that instead of changing what object x is holding, you're altering the object itself that x is holding.

您可以根据 = 左侧的内容来区分这两种情况.如果左边是一个简单的变量名( x = ),则是简单的重新分配.如果左侧使用 [] ( x [0] = )或其他任何类型的访问器"语法,例如.( x.attr = ),您正在更改 x 持有的对象.

You can tell the two cases apart based on what's on the left of =. If the left is a simple variable name (x =), it's a plain reassignment. If the left side uses [] (x[0] =) or anything other kind of "accessor" syntax like a . (x.attr =), you're altering the object that x is holding.

这篇关于X = Y =列表与数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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