What is a=b=c in python? [duplicate]

断了今生、忘了曾经 提交于 2020-06-13 19:31:47

问题


I am quite confused, consecutive equal = can be used in python like:

a = b = c

What is this language feature called? Is there something I can read about that?

Can it be generated into 4 equals?

a = b = c = d

回答1:


This is just a way to declare a and b as equal to c.

>>> c=2
>>> a=b=c
>>> a
2
>>> b
2
>>> c
2

So you can use as much as you want:

>>> i=7
>>> a=b=c=d=e=f=g=h=i

You can read more in Multiple Assignment from this Python tutorial.

Python allows you to assign a single value to several variables simultaneously. For example:

a = b = c = 1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:

a, b, c = 1, 2, "john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.


There is also another fancy thing! You can swap values like this: a,b=b,a:

>>> a=2
>>> b=5
>>> a,b=b,a
>>> a
5
>>> b
2



回答2:


python support multi variable assignment at a time called multiassignment.

In [188]: a = b = c = d = 4

In [189]: a
Out[189]: 4

In [190]: b
Out[190]: 4

In [191]: c
Out[191]: 4

In [192]: d
Out[192]: 4

In [193]: a = 2

In [194]: b = 2

is same as for immutable object

In [195]: a, b = 2 #int is a immutable object like `tuple`, `str`

while this is not to be mean for mutable object like list, dictionary read about mutable and immutable



来源:https://stackoverflow.com/questions/27272034/what-is-a-b-c-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!