单下划线“_”的用途是什么? Python 中的变量?

发布于 2024-11-05 04:46:19 字数 146 浏览 4 评论 0原文

这段代码中for后面的_是什么意思?

if tbh.bag:
    n = 0
    for _ in tbh.bag.atom_set():
        n += 1

What is the meaning of _ after for in this code?

if tbh.bag:
    n = 0
    for _ in tbh.bag.atom_set():
        n += 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

笔落惊风雨 2024-11-12 04:46:19

_ 在 Python 中有 3 个主要的常规用途:

  1. 在交互式中保存最后执行的表达式的结果
    解释器会话(请参阅文档)。这个先例是由标准 CPython 开创的
    口译员,其他口译员也纷纷效仿

  2. 对于 i18n 中的翻译查找(请参阅
    gettext
    例如文档),如代码所示

    raise forms.ValidationError(_("请输入正确的用户名"))
    
  3. 作为通用“一次性”变量名称:

    1. 表示该部分
      函数结果的值被故意忽略(从概念上讲,它被丢弃。),如代码所示:

      label, has_label, _ = text.partition(':')
      
    2. 作为函数定义的一部分(使用 deflambda),其中
      签名是固定的(例如通过回调或父类 API),但是
      这个特定的函数实现不需要所有的
      参数,如代码所示:

      def 回调(_):
          返回真
      

      [很长一段时间以来,这个答案都没有列出这个用例,但它经常出现,正如所指出的此处的目的值得明确列出。]

    此用例可能与翻译查找用例冲突,因此有必要避免在任何也将其用于 i18n 翻译的代码块中使用 _ 作为一次性变量(许多人更喜欢使用双下划线,__,作为他们的一次性变量正是这个原因)。

    Linter 经常认识到这种用例。例如,如果稍后在代码中未使用 dayyear、month、day = date() 将引发 lint 警告。如果确实不需要day,则修复方法是编写year, Month, _ = date()。与 lambda 函数相同,lambda arg: 1.0 创建一个需要一个参数但不使用它的函数,该函数将被 lint 捕获。修复方法是编写lambda _: 1.0。未使用的变量通常会隐藏错误/拼写错误(例如设置 day 但在下一行中使用 dya)。

    Python 3.10 中添加的模式匹配功能将这种用法从“约定”提升为“语言语法”,其中涉及 match 语句:在匹配情况下,_通配符模式,运行时甚至不绑定值到符号这种情况。

    对于其他用例,请记住 _ 仍然是有效的变量名称,因此仍然会使对象保持活动状态。如果这是不可取的(例如释放内存或外部资源),显式的 del name 调用将满足 linter 正在使用该名称的要求,立即清除引用到对象。

_ has 3 main conventional uses in Python:

  1. To hold the result of the last executed expression in an interactive
    interpreter session (see docs). This precedent was set by the standard CPython
    interpreter, and other interpreters have followed suit

  2. For translation lookup in i18n (see the
    gettext
    documentation for example), as in code like

    raise forms.ValidationError(_("Please enter a correct username"))
    
  3. As a general purpose "throwaway" variable name:

    1. To indicate that part
      of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:

      label, has_label, _ = text.partition(':')
      
    2. As part of a function definition (using either def or lambda), where
      the signature is fixed (e.g. by a callback or parent class API), but
      this particular function implementation doesn't need all of the
      parameters, as in code like:

      def callback(_):
          return True
      

      [For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]

    This use case can conflict with the translation lookup use case, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).

    Linters often recognize this use case. For example year, month, day = date() will raise a lint warning if day is not used later in the code. The fix, if day is truly not needed, is to write year, month, _ = date(). Same with lambda functions, lambda arg: 1.0 creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write lambda _: 1.0. An unused variable is often hiding a bug/typo (e.g. set day but use dya in the next line).

    The pattern matching feature added in Python 3.10 elevated this usage from "convention" to "language syntax" where match statements are concerned: in match cases, _ is a wildcard pattern, and the runtime doesn't even bind a value to the symbol in that case.

    For other use cases, remember that _ is still a valid variable name, and hence will still keep objects alive. In cases where this is undesirable (e.g. to release memory or external resources) an explicit del name call will both satisfy linters that the name is being used, and promptly clear the reference to the object.

咆哮 2024-11-12 04:46:19

它只是一个变量名,Python 中通常使用 _ 来表示一次性变量。它只是表明循环变量实际上没有被使用。

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

梦明 2024-11-12 04:46:19

下划线_在Python中被视为“我不在乎”或“一次性”变量

  • Python解释器存储最后一个表达式名为 _ 的特殊变量的值。

    <前><代码>>>> 10
    10

    >>>>> _
    10

    >>>>> _ * 3
    30

  • 下划线_也用于忽略特定值。如果您不需要特定值或未使用这些值,只需将值分配给下划线即可。

    解压时忽略一个值

    <前><代码>x, _, y = (1, 2, 3)

    >>>>> x
    1

    >>>>> y
    3

    忽略索引

    对于范围 (10) 内的 _:
        做某事()
    

Underscore _ is considered as "I don't care" or "throwaway" variable in Python

  • The python interpreter stores the last expression value to the special variable called _.

    >>> 10
    10
    
    >>> _
    10
    
    >>> _ * 3
    30
    
  • The underscore _ is also used for ignoring the specific values. If you don’t need the specific values or the values are not used, just assign the values to underscore.

    Ignore a value when unpacking

    x, _, y = (1, 2, 3)
    
    >>> x
    1
    
    >>> y
    3
    

    Ignore the index

    for _ in range(10):
        do_something()
    
青朷 2024-11-12 04:46:19

Python中使用下划线有5种情况。

  1. 用于存储解释器中最后一个表达式的值。

  2. 用于忽略特定值。 (所谓“我不在乎”)

  3. 为变量或函数的名称赋予特殊的含义和功能。

  4. 用作“国际化 (i18n)”或“本地化 (l10n)”功能。

  5. 分隔数字文字值的数字。

这里是一篇很好的文章,其中包含 mingrammer

There are 5 cases for using the underscore in Python.

  1. For storing the value of last expression in interpreter.

  2. For ignoring the specific values. (so-called “I don’t care”)

  3. To give special meanings and functions to name of variables or functions.

  4. To use as ‘internationalization (i18n)’ or ‘localization (l10n)’ functions.

  5. To separate the digits of number literal value.

Here is a nice article with examples by mingrammer.

计㈡愣 2024-11-12 04:46:19

对于Python语言来说,_一般没有特殊含义。它是一个有效的标识符,就像_foofoo__f_o_o_
唯一的例外是 Python 3.10 以来的 match 语句:

match 语句内的 case 模式中,_ 是表示通配符的软关键字。 来源

否则,_ 纯粹是按照惯例。有几种常见情况:

  • 当不打算使用变量但语法/语义需要名称时,使用虚拟名称。

    # 忽略内容的迭代
    sum(1 for _ in some_iterable)
    # 解包时不考虑特定元素
    头,*_ = 值
    # 函数忽略其参数
    def回调(_):返回True
    
  • 许多 REPL/shell 将最后一个顶级表达式的结果存储到 builtins._

    <块引用>

    特殊标识符_用于交互式解释器中,用于存储上次求值的结果;它存储在builtins 模块中。当不处于交互模式时,_没有特殊含义并且未定义。 [来源]

    由于名称的查找方式,除非被全局或本地 _ 定义遮蔽,否则裸露的 _ 引用 builtins._ .

    <前><代码>>>> 42
    42
    >>>>> f'最后一个答案是{_}'
    “最后的答案是 42”
    >>>>> _
    “最后的答案是 42”
    >>>>> _ = 4 # 带有全局 ``_`` 的影子``builtins._``
    >>>>> 23
    23
    >>>>> _
    4

    注意:某些 shell(例如 ipython)不会分配给 builtins._,而是分配特殊情况的 _ .

  • 在国际化和本地化上下文中,_ 用作主要翻译功能的别名。

    <块引用>

    gettext.gettext(消息)

    根据当前全局域、语言和区域设置目录返回消息的本地化翻译。此函数在本地命名空间中通常别名为 _()(请参阅下面的示例)。

As far as the Python languages is concerned, _ generally has no special meaning. It is a valid identifier just like _foo, foo_ or _f_o_o_.
The only exception are match statements since Python 3.10:

In a case pattern within a match statement, _ is a soft keyword that denotes a wildcard. source

Otherwise, any special meaning of _ is purely by convention. Several cases are common:

  • A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
    
  • Many REPLs/shells store the result of the last top-level expression to builtins._.

    The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. [source]

    Due to the way names are looked up, unless shadowed by a global or local _ definition the bare _ refers to builtins._ .

    >>> 42
    42
    >>> f'the last answer is {_}'
    'the last answer is 42'
    >>> _
    'the last answer is 42'
    >>> _ = 4  # shadow ``builtins._`` with global ``_``
    >>> 23
    23
    >>> _
    4
    

    Note: Some shells such as ipython do not assign to builtins._ but special-case _.

  • In the context internationalization and localization, _ is used as an alias for the primary translation function.

    gettext.gettext(message)

    Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文