I'd like to do something like this:
x = f(a[0]) or f(a[1]) or f(a[2]) or f(a[3]) or …
with a given list a
and a given function f
. Unlike the built-in any
function I need to get the first value of the list which is considered to be true; so for 0 or "foo" or 3.2
I need to get "foo"
, not just True
.
Of course, I could write a small function like
def returnFirst(f, a):
for i in a:
v = f(i)
if v:
return v
return False
x = returnFirst(f, a)
but that's probably not the nicest solution, for reasons also given in this SO question. As I mention this other thread, I could of course use code based on the
solution given there, e.g.
x = next((f(x) for x in a if f(x)), False)
But I don't see a simple way to circumvent the doubled calling of f
then.
Is there any simple solution I am missing or just don't know? Something like an
OR((f(x) for x in a))
maybe?
I tried to find other questions concerning this, but searching for keywords like or
is a bit problematic in SO, so maybe I just didn't find something appropriate.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…