下划线 _ 作为 Python 中的变量名 [英] Underscore _ as variable name in Python
问题描述
Peter Norvig 有一篇文章描述了一个解决数独谜题的程序,即使是最难的数独谜题,通过组合确定性逻辑操作和可能解决方案的智能遍历.后者是递归完成的;这是该函数(source):
Peter Norvig has an essay describing a program to solve sudoku puzzles, even the hardest ones, by combining deterministic logical operations and smart traversal of the possible solutions. The latter is done recursively; here's that function (source):
def search(values):
"Using depth-first search and propagation, try all possible values."
if values is False:
return False ## Failed earlier
if all( len( values[s]) == 1 for s in squares):
return values ## Solved!
## Chose the unfilled square s with the fewest possibilities
_,s = min( (len( values[s]), s)
for s in squares
if len(values[s]) > 1
)
return some( search( assign( values.copy(), s, d))
for d in values[s]
)
(为了我的眼睛,我添加了一些空格、CR 和制表符;向 Norvig 博士道歉.)
(I've added some spaces, CRs, and tabs for the sake of my eyes; apologies to Dr. Norvig.)
在评论的正下方有一行以_,s
"开头.这似乎是具有 s
最小值的解包元组 (len(values[s]),s
).Norvig 博士使用_
"作为变量名只是为了表明这是一个无关紧要"的结果,还是其他原因?是否有时会推荐_
"作为变量名?在交互模式下,_
"保存着上一个操作的答案;非交互式代码中是否有类似的功能?
Right below the comment there's a line starting with "_,s
". That seems to be the unpacked tuple (len(values[s]),s
) with the minimal value of s
. Is Dr. Norvig using "_
" as a variable name just to indicate it's a "don't care" result, or is something else going on? Are there times when "_
" is recommended as a variable name? In interactive mode, "_
" holds the answer of the previous operation; is there a similar function in non-interactive code?
感谢您的好回答.我想答案是亚历克斯·马泰利的增值";他指出,_, vbl_of_interest"习语通常是 DSU 习语的副作用,而 DSU 习语本身在很大程度上是不必要的.
Thanks for the good answers. I guess The Answer goes to Alex Martelli for "value added"; he points out that the "_, vbl_of_interest" idiom is often a side effect of the DSU idiom, which itself has been made largely unnecessary.
推荐答案
是的,_
是don't care"的传统名称(不幸的是,这与它在 I18N 中的使用冲突,但这就是一个单独的问题;-).顺便说一句,在今天的 Python 中,而不是:
Yep, _
is a traditional name for "don't care" (which unfortunately clashes with its use in I18N, but that's a separate issue;-). BTW, in today's Python, instead of:
_,s = min( (len( values[s]), s)
for s in squares
if len(values[s]) > 1
)
你可以编码
s = min((s for s in squares if len(values[s])>1),
key=lambda s: len(values[s]))
(不知道 Peter 写的是什么版本的 Python,但他使用的习语是decorate-sort-undecorate"[[DSU]] 的一个例子,除了 min 而不是 sort,在今天的 Python 中,key=
可选参数通常是执行 DSU 的最佳方式;-).
(not sure what release of Python Peter was writing for, but the idiom he's using is an example of "decorate-sort-undecorate" [[DSU]] except with min instead of sort, and in today's Python the key=
optional parameter is generally the best way to do DSU;-).
这篇关于下划线 _ 作为 Python 中的变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!