在交互式翻译中,_
始终指最后输出的值:
>>> 1 + 1
2
>>> print _
2
>>> 2 + 2
4
>>> print _
4
>>>
In normal Python1 code however, _
is just a typical name. You can assign to it as you would any other:
_ = 3
print _
# Output: 3
虽然我不建议实际这样做,因为_
是一个可怕的名字。此外,按照惯例,它用来表示只是占位符的名称。一个例子是:
a, _, b = [1, 2, 3]
它使用_
意思是我们对此不感兴趣2
。另一个例子是:
for _ in range(10):
function()
这意味着我们没有在循环内使用计数器变量。相反,我们只希望 Python 调用function
十次并且需要_
具有有效的语法。
1By "Python", I mean CPython, which is the standard flavor of the language. Other implementations may choose to do things differently. IPython for example has this to say about underscore-only names:
以下 GLOBAL 变量始终存在(因此不要覆盖
他们!):
[_] (a single underscore) : stores previous output, like Python’s default interpreter.
[__] (two underscores): next previous.
[___] (three underscores): next-next previous.
Source: http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/reference.html#output-caching-system http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/reference.html#output-caching-system