I'm still new to python and I was wondering if there was a way to simplify this function into something close to a one-liner:
filters = [lambda x: is_big(x), lambda x: is_wide(x), lambda x: is_gray(x)]
def filter(input):
for func in filters:
if(not func(input)):
return False
else:
continue
return True
Assume the functions in the filters list return booleans. Basically is there any way I can do something like all(apply input to each filter)
?
all(func(input) for func in filters)
是的,您可以使用all()
:
result = all(f(input) for f in filters)
Here's a list comprehension to get filtered output from your input:
filtered = [x for x in input if all(f(x) for f in filters)]
You could also use the built in filter:
complete_filter = lambda x: all(f(x) for f in filters)
filtered = filter(complete_filter, input)
On a side note (not sure what others mean by the fact that all
doesn't short circuit). See below:
def f():
print "in f"
return True
def g():
print "in g"
return False
def h():
print "in h"
return True
filters = [f, g, h]
print all(fn() for fn in filters)
This prints
in f
in g
False
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.