Meaning of using commas and underscores with Python assignment operator?

天涯浪子 提交于 2019-12-17 04:57:31

问题


Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.

I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as

def f():
    return 1,2

a, b = f()

But what is the meaning of each of the following?

d2, = values[s]  ## values[s] is a string and at this point len(values[s]) is 1

If len(values[s]) == 1, then how is this statement different than d2 = values[s]?

Another question about using an underscore in the assignment here:

_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)

Does the underscore have the effect of basically discarding the first value returned in the list?


回答1:


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.




回答2:


_ 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



回答3:


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.




回答4:


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

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

>>> (2)*2
4


来源:https://stackoverflow.com/questions/1708292/meaning-of-using-commas-and-underscores-with-python-assignment-operator

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