我有一个正则表达式列表和一个目标短语列表。我希望将每条正则表达式与每个短语进行匹配,返回一个列表列表,其中行是术语,列是正则表达式,数据是匹配对象或None
尽可能简洁。我目前的方法进行了这种匹配,但不幸的是给了我一个长列表,而不是我描述的列表列表。
这是我所拥有的:
import re
regexLines=['[^/]*/b/[^/]*', 'a/[^/]*/[^/]*', '[^/]*/[^/]*/c', 'foo/bar/baz', 'w/x/[^/]*/[^/]*', '[^/]*/x/y/z']
targetLines=['/w/x/y/z/', 'a/b/c', 'foo/', 'foo/bar/', 'foo/bar/baz/']
###compiling the regex lines
matchLines=[re.compile(i) for i in regexLines]
matchMatrix=[i.match(j) for i in matchLines for j in targetLines]
matchMatrix
[None, <_sre.SRE_Match object at 0x04095368>, None, None, None, None, <_sre.SRE_Match object at 0x0411A3D8>, None, None, None, None, <_sre.SRE_Match object at 0x0411A410>, None, None, None, None, None, None, None, <_sre.SRE_Match object at 0x0411A448>, None, None, None, None, None, None, None, None, None, None]
相反,我想要看起来像这样的东西,每一行代表一个短语的匹配项:
[[None, <_sre.SRE_Match object at 0x04095368>, None, None, None, None],
[<_sre.SRE_Match object at 0x0411A3D8>, None, None, None, None, <_sre.SRE_Match object at 0x0411A410>], etc. etc.
我可以写出一个详细的循环来做我想做的事情,但我的想法是有一种简洁的 Pythonic 方式来做到这一点。