Python 中的 _ 有什么作用? [英] What does _ in Python do?
问题描述
我在某个地方看到了 Python 中使用的 _
字符,例如:
print _
有人可以帮我解释一下它的作用吗?
在交互式解释器中,_
总是指最后输出的值:
在普通的 Python1 代码中,_
只是一个典型的名字.您可以像其他任何人一样分配给它:
_ = 3打印 _# 输出:3
虽然我不建议实际这样做,因为 _
是一个糟糕的名字.此外,按照惯例,它用于表示一个名称,它只是一个占位符.一个例子是:
a, _, b = [1, 2, 3]
使用 _
表示我们对 2
不感兴趣.另一个例子是:
for _ in range(10):功能()
这意味着我们没有在循环内使用 counter 变量.相反,我们只希望 Python 调用 function
十次,并且需要 _
具有有效的语法.
1Python"是指 CPython,它是该语言的标准风格.其他实现可能会选择以不同的方式做事.例如,IPython 有关于仅下划线名称的说法:
<块引用>以下 GLOBAL 变量始终存在(所以不要覆盖他们!):
[_](单下划线):存储之前的输出,就像 Python 的默认解释器.[__](两个下划线):下一个上一个.[___](三个下划线):下一个下一个上一个.
来源:http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/reference.html#output-caching-system
I saw somewhere about the _
character being used in Python like:
print _
Can somebody help me explain what it does?
In the interactive interpreter, _
always refers to the last outputed value:
>>> 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
Although I wouldn't recommend actually doing this because _
is a terrible name. Also, it is used by convention to mean a name that is simply a placeholder. An example would be:
a, _, b = [1, 2, 3]
which uses _
to mean that we are not interested in the 2
. Another example is:
for _ in range(10):
function()
which means that we are not using the counter variable inside the loop. Instead, we only want Python to call function
ten times and need the _
to have valid syntax.
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:
The following GLOBAL variables always exist (so don’t overwrite them!):
[_] (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
这篇关于Python 中的 _ 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!