【问题标题】:Python Underscore Inside List列表内的 Python 下划线
【发布时间】:2020-03-29 15:43:37
【问题描述】:

我意识到下划线用于许多情况,例如 python 中的一次性变量。

我最近遇到了以下示例:

a = [1, 2, 5, 3]
a[_]

现在第二行返回一个 2。这是怎么回事? 编辑:

在 Jupyter Notebook 中,以下示例应该可以工作:

a = [1, 2, 3]

for _ in range(2):
    print(a[_])

a[_]

这个输出:

1
2
2

但肯定 a[_] 中的 _ 应该超出范围吗?

【问题讨论】:

  • 请在上面显示一些代码。其他方式你应该得到一个错误NameError: name '_' is not defined
  • @BearBrown 不正确,在 IPython shell 中使用 _ 将是有效的,但不管我们需要查看一些代码
  • @gold_cy ipython 运行一些魔法,所以它与 python 不同。
  • @BearBrown OP 从未指定 在哪里他在运行这个,IPython 仍然是 Python
  • 在我的原始帖子中添加了更多详细信息

标签: python list numpy jupyter-notebook slice


【解决方案1】:

在许多情况下,我也认为这种情况下,_ 表示最后创建的值,而与变量类型无关。例如,在尝试在 Ipython 中复制它时,我创建了列表 a,然后尝试通过 _ 引用其中一个元素。由于我创建的最后一个变量是一个列表,因此失败了:

In [99]: a = [1, 2, 3, 4]                                                                                                                                                                                               

In [100]: a[_]                                                                                                                                                                                                          
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-100-81d8b9395518> in <module>
----> 1 a[_]

TypeError: list indices must be integers or slices, not list

在您的for 循环中,您假设目标变量在整个for 循环的范围内,然后超出范围。不是这种情况。 for 循环中目标值的最后一个值不是垃圾收集或删除的。

a = [1, 2, 3]

for _ in range(2):
    print(a[_])

a[_] 

1       # index 0, points at a value of one.
2       # index 1, points at a value of two.
2       # we have left the for loop, but the _ still points at the
        #     last value it was associated with, a 1 and thus 
        #     the list indexing expression retrieves a value of two.

这是显示这种现象在工作中的另一个示例:

In [109]: for word in ['alpha', 'beta', 'zeta']: 
     ...:     print(word) 
     ...:                                                                                                                                                                                                               
alpha
beta
zeta

In [110]: word         # let's examine word outside the for loop:                                                                                                                                                                                                    
Out[110]: 'zeta'

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多