【问题标题】:most concise way to operate over two lists, returning list of lists in python对两个列表进行操作的最简洁方法,在 python 中返回列表列表
【发布时间】: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


    【解决方案1】:

    可能是你想要的:

    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]]
    

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 2023-04-09
      • 1970-01-01
      • 2011-11-21
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多