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

此代码中的_after 是什么意思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

回答 0

_ 在Python中有4种主要的常规用法:

  1. 在交互式解释器会话中保存上次执行的表达式的结果。此先例是由标准CPython解释器设置的,其他解释器也纷纷效仿
  2. 有关在i18n中进行翻译查找的信息,请参见 gettext 例如,文档),如代码所示: raise forms.ValidationError(_("Please enter a correct username"))
  3. 作为通用“一次性”的变量名指示函数结果的一部分被故意忽略(在概念上,它被丢弃。),如类似的代码: label, has_label, _ = text.partition(':')
  4. 作为函数定义的一部分(使用deflambda),其中的签名是固定的(例如,通过回调或父类API),但是此特定函数实现不需要所有参数,如代码所示:callback = lambda _: True

(很长一段时间以来,这个答案只列出了前三个用例,但是第四个用例经常出现,如前所述 这里,将值得明确列出)

后者的“抛弃型变量或参数名称”用例可能与翻译查找用例冲突,因此有必要避免_在也将其用于i18n转换的任何代码块中将其用作抛弃型变量(许多人更喜欢双下划线,__正是由于这个原因而将其作为一次性变量)。

_ has 4 main conventional uses in Python:

  1. To hold the result of the last executed expression(/statement) in an interactive interpreter session. 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 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(':').
  4. 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: callback = lambda _: True

(For a long time this answer only listed the first three use cases, but the fourth case came up often enough, as noted here, to be worth listing explicitly)

The latter “throwaway variable or parameter name” uses cases 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).


回答 1

它只是一个变量名,在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.


回答 2

下划线在Python中_被视为“ 我不在乎 ”或“ 抛出 ”变量

  • python解释器将最后一个表达式值存储到名为的特殊变量中_

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

    开箱时忽略值

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

    忽略索引

    for _ in range(10):     
        do_something()

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()
    

回答 3

在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 vartiables 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.


回答 4

就Python语言而言,_没有特殊含义。与或一样,它是有效的标识符_foofoo__f_o_o_

的任何特殊含义_纯属约定。常见几种情况:

  • 如果不打算使用变量,但是语法/语义需要一个虚拟名称。

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
  • 许多REPL / shell将最后一个顶级表达式的结果存储到builtins._

    特殊的标识符_在交互式解释器中用于存储上一次评估的结果。它存储在builtins模块中。如果不在交互模式下,_则没有特殊含义并且未定义。[ 来源 ]

    由于查找名称的方式,除非由全局或局部_定义遮盖,否则裸_指的是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

    注意:某些外壳程序(例如)ipython不分配给builtins._而是特例_

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

    gettext.gettext(消息)

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

As far as the Python languages is concerned, _ has no special meaning. It is a valid identifier just like _foo, foo_ or _f_o_o_.

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).


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。