[英]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 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? 有类似的东西已经在Python中可用,还是有更惯用的方法来做到这一点?
[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. Python lambda只是它们的LISP对应物的一小部分。
In python lambdas cannot include blocks, so the for loop is not possible for a lambda 在python中,lambdas不能包含块,因此for循环不可能用于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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.