【发布时间】:2019-06-24 10:10:46
【问题描述】:
检查正则表达式表示的某个元素是否在给定列表中的最快和优雅的方法。
例如: 给定一个列表:
newlist = ['this','thiis','thas','sada']
regex = re.compile('th.s')
在这个问题中:Regular Expressions: Search in list
list(filter(regex.match,newlist))
给我一份清单
['this','thas']
但是,我只想返回 True 或 False。因此,上述方法效率不高,因为它会查看 newlist 的所有元素。有没有办法像
'this' in newlist
高效优雅地检查正则表达式表示的某个元素是否在给定列表中。
【问题讨论】:
-
首先使用
regex可能不是最有效的方法... -
使用
any()而不是filter()? -
从 newlist 中创建一个字符串:
,this,thiis,thas,sada,。保留它,然后运行 findall(),或使用新构造的正则表达式,(th.s),进行单个匹配。这将为您提供['this','thas']或 TRUE/FALSE,而无需迭代。 -
@Loocid 你的意思是任何(过滤器(regex.match,newlist))?它仍然会查看 newlist 的所有元素以返回“True or False”,对吧?
-
@Loocid 你的意思是在 python3 中 filter() 给了我一个迭代器而不是一个完整的列表,因此当我合成 any() 时,如果不是最坏的情况,它不会遍历所有元素的新列表返回 True?
标签: regex python-3.x