我在Python中的冒险经历继续,我最喜欢的书再次沉默.Python提供了一种内置方法,使用'in'关键字测试变量是否在可迭代对象中:
if "a" in "abrakadabra" :
print "it is definitely here"
Run Code Online (Sandbox Code Playgroud)
但是有可能测试列表中是否有多个项目(任何一个)?目前,我正在使用下面的语法,但它有点长:
if "// @in " in sTxt or "// @out " in sTxt or "// @ret " in sTxt or <10 more>
print "found."
Run Code Online (Sandbox Code Playgroud)
当然正则表达式可以提供帮助,但使用正则表达式会占用大量代码,并且不会像"a in b"那样清晰.还有其他Pythonic方式吗?
Mar*_*rot 46
alternatives = ("// @in ", "// @out ", "// @ret ")
if any(a in sTxT for a in alternatives):
print "found"
if all(a in sTxT for a in alternatives):
print "found all"
Run Code Online (Sandbox Code Playgroud)
any()并all()采用iterable并检查其中是否有任何/所有值都计算为真值.将它与生成器表达式相结合,您可以检查多个项目.
如果您正在为相同的单词测试许多行,则将它们编译为正则表达式可能会更快.例如:
import re
words = ["// @in ", "// @out ", "// @ret "] + ["// @test%s " % i for i in range(10)]
my_regex = re.compile("|".join(map(re.escape, words)))
for line in lines_to_search:
if my_regex.search(line): print "Found match"
Run Code Online (Sandbox Code Playgroud)
一些快速计时表明,这通常比any(word in theString for word in words)方法更快.我用不同的文本测试了两种方法(短/长有/无匹配).结果如下:
{ No keywords } | {contain Keywords }
short long short long
regex : 0.214 27.214 0.147 0.149
any in : 0.579 81.341 0.295 0.300
Run Code Online (Sandbox Code Playgroud)
如果性能无关紧要,那么这种any()方法更具可读性.
| 归档时间: |
|
| 查看次数: |
10815 次 |
| 最近记录: |