【发布时间】:2014-05-12 22:18:16
【问题描述】:
看看下面这段代码:
class a:
s = 'python'
b = ['p', 'y']
c = [x for x in s]
输出:
>>> a.c
['p', 'y', 't', 'h', 'o', 'n']
但是当我尝试使用 if 限制列表时:
class a:
s = 'python'
b = ['p', 'y']
c = [x for x in s if x in b]
显示以下异常:
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
class a:
File "<pyshell#22>", line 4, in a
c = [x for x in s if x in b]
File "<pyshell#22>", line 4, in <listcomp>
c = [x for x in s if x in b]
NameError: global name 'b' is not defined
如果 make global b 有效,为什么会这样?
【问题讨论】:
标签: python scope list-comprehension