开发者

Lisp's "some" in Python?

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 fi开发者_如何学编程lters. 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?


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


[s for s in strings if any(re.match (f, s) for f in filters)]


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜