python - 为什么“_”在交互式 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
所以我想我的问题是为什么?为什么会这样?为什么_
有时可以更改它并不意味着最后的结果?
解决方案
原因很简单-尝试做
[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
推荐阅读
- kibana - Kibana - 查找 http-URL
- microsoft-graph-api - 无法访问 onedrive 内容
- typescript - Intellij TypeScript 变量名称自动完成
- c++ - 如何管理单例类中的变量状态?
- loops - 在嵌套循环中添加动态主机时 Ansible include_tasks 出错
- couchdb - 高级查询 - 部分匹配
- python-3.x - 将非结构化的txt文件读入数据框
- r - 如何修复:“CA(dt, graph = FALSE) 中的错误:以下变量不是定量 Var1”
- c# - Protobuf-net 反序列化问题
- iframe - 如何修复“阻止来自“https://example.org”的框架访问跨域框架。”