首页 > 解决方案 > 为什么“_”在交互式 shell 中并不总是给我最后的结果

问题描述

通常我_用来访问 Python 交互式 shell 中的最后一个结果。特别是快速将变量分配给我认为以后可能很重要的结果。

我最近发现的是,如果我_在 for 循环中使用作为值,我不能再使用它_来引用最后一个结果。

例子:

>>> for _ in range(10):
...   pass
...
>>> 120
120
>>> a=_
>>> a
9
>>> _
9
>>> del _ # Now I can use _ to reference the last result again
>>> 120
120
>>> a=_
>>> a
120

如果我使用空白的 for 循环,那么_在我删除它之前不能将其视为最后一个结果,然后它就可以工作了。

如果我列出理解,尽管它似乎仍然可以正常工作:

>>> [1 for _ in range(10)]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> 120
120
>>> a=_
>>> a
120    

所以我想我的问题是为什么?为什么会这样?为什么_有时可以更改它并不意味着最后的结果?

标签: pythonpython-3.x

解决方案


原因很简单-尝试做

[i for i in range(1000)]

and then accessing i- you'll see that i isn't defined (it's scope is within the list comprehension- when you exit the list comprehension, there "is no i").

This is in contrast to a for loop, where the scope of i is NOT within the actual for loop- so you can access it from outside.

So if we go to your case (with the _), if the _ is defined, like with a regular for loop, then you need to del it. If you do it within a list comprehension, once the list comprehension is over, the underscore is no longer defined- which means it'll just be the last value


推荐阅读