如何在列表理解中使用重新匹配对象 [英] How to use re match objects in a list comprehension

查看:89
本文介绍了如何在列表理解中使用重新匹配对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从字符串列表中选出块并将其作为另一个列表返回的功能:

I have a function to pick out lumps from a list of strings and return them as another list:

def filterPick(lines,regex):
    result = []
    for l in lines:
        match = re.search(regex,l)
        if match:
            result += [match.group(1)]
    return result

有没有一种方法可以将其重新表达为列表理解?显然,这是很清楚的;只是好奇.

Is there a way to reformulate this as a list comprehension? Obviously it's fairly clear as is; just curious.

感谢那些贡献者,特别感谢@Alex.这是我最后得到的简明版本. regex match方法作为预悬挂"参数传递给filterPick:

Thanks to those who contributed, special mention for @Alex. Here's a condensed version of what I ended up with; the regex match method is passed to filterPick as a "pre-hoisted" parameter:

import re

def filterPick(list,filter):
    return [ ( l, m.group(1) ) for l in list for m in (filter(l),) if m]

theList = ["foo", "bar", "baz", "qurx", "bother"]
searchRegex = re.compile('(a|r$)').search
x = filterPick(theList,searchRegex)

>> [('bar', 'a'), ('baz', 'a'), ('bother', 'r')]

推荐答案

[m.group(1) for l in lines for m in [regex.search(l)] if m]

技巧"是for m in [regex.search(l)]部分-在列表理解中,这就是您分配"您需要多次使用的值的方式-仅添加这样的子句,其中对象迭代"在一个单项列表中,该列表包含您要分配"给它的一个值.有人认为这在样式上令人怀疑,但有时我觉得很实用.

The "trick" is the for m in [regex.search(l)] part -- that's how you "assign" a value that you need to use more than once, within a list comprehension -- add just such a clause, where the object "iterates" over a single-item list containing the one value you want to "assign" to it. Some consider this stylistically dubious, but I find it practical sometimes.

这篇关于如何在列表理解中使用重新匹配对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆