【发布时间】:2013-10-29 02:14:06
【问题描述】:
我有一个正则表达式列表和一个目标短语列表。我希望将每条正则表达式与每个短语进行匹配,返回一个列表列表,其中行是术语,列是正则表达式,数据是匹配对象或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 方式来执行此操作。
【问题讨论】:
标签: python regex list iterator