我正在尝试定义一个函数,如果模式与列表中的所有字符串匹配,则返回True。像是matchAll(pattern,list)。
我最初的尝试是:
import re
def matchAll(pattern, list):
list_truth = list
for i in list:
list_truth[i] = re.search(pattern,i) != none
if False in list_truth:
return False
else:
return True
但是,它不起作用。请让我知道我做错了哪一部分。非常感谢!
例如,样本输入/输出看起来像:
print matchAll('a', ['a', 'ab', 'abc']) # True
print matchAll('a', ['a', 'ab', 'bc']) # False
print matchAll('(ab)?', ['a', 'ab', 'abc']) # True
print matchAll('.', ['a', 'ab', 'abc']) # True
print matchAll('.{2,3}', ['a', 'ab', 'abc']) # False
我也将代码修改为:
import re
def matchAll(pattern, list1):
list_truth = list
for i in list1:
if re.search(pattern,i) != None:
pass
else:
return False
return True
但是,它返回正确的结果,但是我认为这不是构造函数的好方法。有人对我如何优化它有想法吗?谢谢!
您可以all
为此使用(Python内置)
def match_all(pattern, items)
return all(re.search(pattern, item) for item in items)
另请注意
list
是内置类型,请避免将其用作变量名re.search
是一个对象(真实)或None
(虚假),这就是为什么该返回值可以用作以下对象的布尔尼的原因:all
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句