如果我有一个字符串列表:
matches = [ 'string1', 'anotherstring', 'astringystring' ]
我还有另一个要测试的字符串:
teststring = 'thestring1'
我想测试每个字符串,如果有任何匹配,就做一些事情。我有:
match = 0
for matchstring in matches:
if matchstring in teststring:
match = 1
if !match:
continue
这是在一个循环中,所以如果我们没有得到匹配,我们就再绕一遍(我当然可以颠倒这个逻辑,如果匹配就做一些事情),但是代码看起来很笨拙,而不是 pythonic,如果简单的话跟随。
我在想有更好的方法来做到这一点,但我并没有像我希望的那样很好地理解 python。有没有更好的方法?
注意“重复”是相反的问题(尽管相同的答案方法是相同的)。
请您参考如下方法:
你可以使用 any这里
代码:
if any(matchstring in teststring for matchstring in matches):
print "Matched"
注意事项:
-
any看到匹配项后立即退出。 - 根据循环发生的事情是
for matchstring in matches这里matches中的每个字符串都被迭代。 - 在这里
matchstring in teststring我们正在检查迭代字符串是否在定义的检查字符串中。 any将在表达式中发现True[match] 时立即退出。
