tags:

views:

157

answers:

3

I have a list of strings and a list of filters (which are also strings, to be interpreted as regular expressions). I want a list of all the elements in my string list that are accepted by at least one of the filters. Ideally, I'd write

[s for s in strings if some (lambda f: re.match (f, s), filters)]

where some is defined as

def some (pred, list):
    for x in list:
        res = pred (x)
        if res:
            return res
    return False

Is something like that already available in Python, or is there a more idiomatic way to do this?

+10  A: 

There is a function called any which does roughly want you want. I think you are looking for this:

[s for s in strings if any(re.match(f, s) for f in filters)]
Mark Byers
+5  A: 
[s for s in strings if any(re.match (f, s) for f in filters)]
Ofri Raviv
+1  A: 

Python lambda's are only a fraction as powerful as their LISP counterparts.

In python lambdas cannot include blocks, so the for loop is not possible for a lambda

I would use a closure so that you dont have to send the list every time

def makesome(list):
    def some(s)
        for x in list:
            if x.match(s): 
                return True
        return False
    return some

some = makesome(list)

[s for s in strings if some(s)]
Fire Crow
Your assessment of Python's lambdas is true, except the fraction is 0.9.
Nathan Sanders
heres a nice perspective on it "Is like watching trailer of a movie. Exciting, but not quite the real thing." http://rapd.wordpress.com/2007/05/09/lambda-in-python/ - though from a lispers perspective, I dont share his enthusiasm for clean code, give me functionality.
Fire Crow