Python 使任何()中使用的变量在外部可见
如何在if语句外打印匹配字符串Python 使任何()中使用的变量在外部可见,python,Python,如何在if语句外打印匹配字符串 strings = ("string1", "string2", "string3") for line in file: if any(s in line for s in strings): print "s is:",s 说: 您可以使用生成器,并调用下一个(..): 正如政府所说: 如果iterable的任何元素为True,则返回True。如果可移植性是 空,返回False 并且您不能访问范围之外的任何(…)(生成器表达式范围)中
strings = ("string1", "string2", "string3")
for line in file:
if any(s in line for s in strings):
print "s is:",s
说:
您可以使用生成器,并调用
下一个(..)
:
正如政府所说:
如果iterable的任何元素为True,则返回True
。如果可移植性是
空,返回False
并且您不能访问范围之外的任何(…)
(生成器表达式范围)中使用的中间变量
为了实现这一点,您可以改为:
strings = ("string1", "string2", "string3")
existed = None
for line in file:
for s in strings:
if s in line:
existed = s
break
if existed:
print "s is:",s
不能,变量只在生成器内部声明。 您必须为此添加另一个for循环:
strings=(“string1”、“string2”、“string3”)
对于文件中的行:
对于字符串中的s:
如果符合下列条件:
打印“s is:”,s
但是您可以使用避免嵌套循环。我同意@Willem Van Onsem的评论
strings = ("string1", "string2", "string3")
for line in file:
result = next((s for s in strings if s in line),None)
if result is not None:
print "s is:",result
这不是任何的用例,只是使用一个循环:
for line in file:
for s in strings:
if s in line:
print "s is:",s
strings = ("string1", "string2", "string3")
existed = None
for line in file:
for s in strings:
if s in line:
existed = s
break
if existed:
print "s is:",s
strings = ("string1", "string2", "string3")
for line in file:
result = next((s for s in strings if s in line),None)
if result is not None:
print "s is:",result