列表理解中的 if 子句在 pdb 中给出未定义的名称错误,但在解释器中没有

if clause in list comprehension gives undefined name error in pdb but not in interpreter

抱歉这个糟糕的标题。我必须弄清楚术语并试图将所有相关点放在那里。

考虑 Python 中的以下简单交互:

Python 3.6.9 (default, Jul 21 2019, 14:33:59) 
[GCC 7.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> python.el: native completion setup loaded
>>> s1 = [ i for i in range(10)]
>>> [i for i in range(len(s1)) if s1[i]%2 == 0]
[0, 2, 4, 6, 8]

最后一条语句创建(并打印)原始数组 s1 中偶数元素的索引。

但等效项在 pdb 中不起作用:

(Pdb) !s1 = [ i for i in range(10)]
(Pdb) s1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
(Pdb) ![i for i in range(len(s1)) if s1[i]%2 == 0]
*** NameError: name 's1' is not defined

为什么 s1 在 python 解释器的范围内而不在调试器中?我正在尝试识别数组中满足特定条件的元素。 python 在调试器中执行此操作的方法是什么?

就像其他人提到的那样,您的代码应该可以工作。但是,前段时间我 运行 遇到了类似的问题,当时我尝试像您一样在列表理解中使用变量,我发现 Antimony 的回复非常有用:

"In Python 3, you have to use the interact command in pdb before you can access any non-global variables due to a change in the way comprehensions are implemented."

List comprehension scope error from Python debugger