我在下面提到的代码中遇到错误:
NameError: name 'x' is not defined
list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=open(filename)
for line in file:
if any(x in line.upper() for x in list_keywords):
print (x)
我可以打印包含列表中提到的任何字符串的行。
下面的代码可以使用。
list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=open(filename)
for line in file:
if any(x in line.upper() for x in list_keywords):
print (line)
有人可以告诉我为什么print(x)不起作用吗?
答案 0 :(得分:7)
在Python 2中,x
泄露进入列表解析中的命名空间(虽然不在生成器表达式中),但不在Python 3中:
Py 2:
>>> [x for x in range(3)]
[0, 1, 2]
>>> x
2
Py 3:
>>> [x for x in range(3)]
[0, 1, 2]
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
无论如何,如果你想获得满足条件的第一个值,那么使用next()
代替所有值,使用列表comprhension,例如
>>> next(x for x in range(5) if x % 2 == 1)
1
>>> [x for x in range(5) if x % 2 == 1]
[1, 3]
答案 1 :(得分:1)
any(x in line.upper() for x in list_keywords)
any
的参数是生成器,x
仅在生成器中定义。
答案 2 :(得分:1)
我不确定你想要什么,但这可能会为您提供所需的信息:
list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=open(filename)
for line in file:
results = [(line,x) for x in list_keywords if x in line.upper()]
if results:
print(results)
我测试了这段代码:
list_keywords=['DROP','CREATE','ALTER','COMMENT']
file=['foo','bar','drop comment','zoo']
for line in file:
results = [(line,x) for x in list_keywords if x in line.upper()]
if results:
print(results)
输出:
[('drop comment', 'DROP'), ('drop comment', 'COMMENT')]