Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

python - Shortcut OR-chain applied on list

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should work:

next((x for y in a for x in (f(y),) if x),False)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...