清单上应用的快捷OR链 [英] Shortcut OR-chain applied on list

查看:58
本文介绍了清单上应用的快捷OR链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

x = f(a[0]) or f(a[1]) or f(a[2]) or f(a[3]) or …

具有给定的列表a和给定的功能f.与内置的any函数不同,我需要获取被认为是true的列表的第一个值;因此对于0 or "foo" or 3.2,我需要获取"foo",而不仅仅是True.

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)

但是我看不到一种简单的方法来规避f的双重调用.

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

也许吗?

我试图找到与此有关的其他问题,但是在搜索中搜索or之类的关键字有点麻烦,所以也许我只是找不到合适的东西.

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.

推荐答案

我现在正在使用它:

x = next((v for v in (f(x) for x in a) if v), False)

这是一个行之有效的习惯用法,没有加倍f的调用,也没有引入hacky local,但是它仍然不是很可读(特别是如果xfav较长)多于一个字母).

It's a working idiom without doubling the call of f and without introducing a hacky local, but it still is not very readable (especially if x, f, a, and v are longer than one letter).

我很高兴听到更好的解决方案.

I'd be happy to hear of a better solution.

这篇关于清单上应用的快捷OR链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆