Meaning of using commas and underscores with Python assignment operator?

喜欢而已 提交于 2019-11-27 00:56:12

d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.

>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>> 

a is tuple, b is an integer.

_ is like any other variable name but usually it means "I don't care about this variable".

The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.

>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2

The _ in the Python shell also refers to the value of the last operation. Hence

>>> 1
1
>>> _
1

The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.

You can use the trailing comma in a tuple like this:

>>> (2,)*2
(2, 2)

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