开发者

Is there a Python equivalent of Ruby's 'any?' function?

In Ruby, you can call Enumerable#any? on a enumerable object to see if any of its elements satisfies the predicate you pass in the block. Like so:

lst.any?{|e| pred(e) }

In Python, there's an any function that does something similar, but on a list of booleans.

Of course, for a reasonably-sized list, I'd just do:

any(map(pred,lst))

However, if my list is very long, I don't want to have to do the entire map operation first.

So, t开发者_开发技巧he question: Is there a generic short-circuiting any function in Python?

Yes, I know it's really trivial to write one myself, but I'd like to use speedy builtin functions (and also not reinvent any wheels).


any(pred(x) for x in lst)

alternatively

from itertools import imap
any(imap(pred, lst))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜