我在Python中发现了关于迭代器行为的这个问题:
Python list iterator behavior and next(iterator)
当我输入代码时:
a = iter(list(range(10)))
for i in a:
print a
next(a)
进入它返回的jupyter-qtconsole
:
0
2
4
6
8
完全和Martijn Pieters说的那样,当解释器没有回应next(a)
的呼叫时。
然而,当我在我的Bash解释器和IDLE中再次运行相同的代码时,代码打印出来了:
0
1
2
3
4
5
6
7
8
9
到控制台。
我运行了代码:
import platform
platform.python_implementation()
在所有三种环境中他们都说我跑了'CPython'
。
那么,为什么QtConsole会在IDLE和Bash没有时禁止next(a)
来电?
如果有帮助,我在Mac OSX上运行Python 2.7.9并使用Anaconda发行版。
答案 0 :(得分:3)
这只是IPython
(QtConsole
所基于的)开发人员选择应该回应给用户的选项。
具体而言,在使用的InteractiveShell
类中,默认情况下,函数run_ast_nodes
使用interactivity='last_expr'
定义。有关此属性的文档说明:
interactivity : str
'all', 'last', 'last_expr' or 'none', specifying which nodes should be
run interactively (displaying output from expressions). 'last_expr'
will run the last node interactively only if it is an expression (i.e.
expressions in loops or other blocks are not displayed. Other values
for this parameter will raise a ValueError.
如您所见: 循环或其他块中的表达式未显示 。
您可以在IPython
的配置文件中更改此设置,如果确实需要,可以像repl
一样使用它。重点是,这只是设计师的偏好。