我有一个正则表达式列表和一个目标短语列表。我希望将每个正则表达式与每个短语匹配,返回一个列表列表,其中行是术语,列是regex,数据是match对象或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.我可以写出一个冗长的循环,可以做我想做的事,但我的暗示是,有一个简洁的,毕达通的方法来做到这一点。
发布于 2013-10-20 16:53:49
也许你想:
matchMatrix = [[i.match(j) for j in targetLines] for i in matchLines ]演示:
>>> import pprint
>>> pprint.pprint([[i.match(j) for j in targetLines] for i in matchLines ])
[[None, <_sre.SRE_Match object at 0x9b5d058>, None, None, None],
[None, <_sre.SRE_Match object at 0x9b5d100>, None, None, None],
[None, <_sre.SRE_Match object at 0x9b5d138>, None, None, None],
[None, None, None, None, <_sre.SRE_Match object at 0x9b5d170>],
[None, None, None, None, None],
[None, None, None, None, None]]https://stackoverflow.com/questions/19480086
复制相似问题