Python 赋值运算符中使用逗号和下划线的含义是什么?
通读 Peter Norvig 的解决每个数独谜题文章,我遇到了一些我从未遇到过的 Python 习惯用法以前见过。
我知道函数可以返回值的元组/列表,在这种情况下,您可以将多个变量分配给结果,例如
def f():
return 1,2
a, b = f()
但是以下各项的含义是什么?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
如果len(values[s]) == 1
,那么此语句与d2 = value[s]
有何不同?
关于在此处的赋值中使用下划线的另一个问题:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
下划线是否具有基本上丢弃列表中返回的第一个值的效果?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在元组中使用尾随逗号,如下所示:
You can use the trailing comma in a tuple like this:
d2, = value[s]
与a,b=f()
类似,只是解包 1 个元素元组。a
是元组,b
是整数。d2, = values[s]
is just likea,b=f()
, except for unpacking 1 element tuples.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.
Python shell 中的 _ 也指最后一次操作的值。因此,
逗号指的是元组拆包。所发生的情况是,返回值是一个元组,因此它被按照元组元素的顺序解压缩到用逗号分隔的变量中。
The _ in the Python shell also refers to the value of the last operation. Hence
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.