Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

syntax - Meaning of using commas and underscores with Python assignment operator?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...