Python中_的作用是什么?

Sal*_*ire 4 python syntax

我在某处看到_了Python中使用的字符:

print _
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解释它的作用吗?

iCo*_*dez 18

在交互式解释器中,_始终引用最后输出的值:

>>> 1 + 1
2
>>> print _
2
>>> 2 + 2
4
>>> print _
4
>>>
Run Code Online (Sandbox Code Playgroud)

但是,在普通的Python 1代码中,_它只是一个典型的名称.你可以像任何其他人一样分配给它:

_ = 3
print _
# Output: 3
Run Code Online (Sandbox Code Playgroud)

虽然我不建议实际这样做,因为这_是一个可怕的名字.此外,按惯例,它用于表示仅占位符的名称.一个例子是:

a, _, b = [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

_意味着我们对此不感兴趣2.另一个例子是:

for _ in range(10):
    function()
Run Code Online (Sandbox Code Playgroud)

这意味着我们没有在循环中使用计数器变量.相反,我们只希望Python调用function十次并且需要_具有有效的语法.


1 "Python",我的意思是CPython,这是该语言的标准风格.其他实现可能选择以不同方式执行操作.例如,IPython有关于仅下划线名称的说法:

以下GLOBAL变量始终存在(因此不要覆盖它们!):

[_] (a single underscore) : stores previous output, like Python’s default interpreter.
[__] (two underscores): next previous.
[___] (three underscores): next-next previous.
Run Code Online (Sandbox Code Playgroud)

资料来源:http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/reference.html#output-caching-system