Can this be written more concisely in a functional style
a.schmolck at gmx.net
Tue Nov 18 18:48:34 CET 2003
tweedgeezer at hotmail.com (Jeremy Fincher) writes:
> jcb at iteris.com (MetalOne) wrote in message news:<92c59a2c.0311172340.544faac6 at posting.google.com>...
> > Maybe my post was not clear.
> > I want a means to test if there exists an element in the list that
> > satisfies a predicate.
> Sure there is. The code that you showed was an excellent way to do
> > Actually, when I word it that way, I guess what I want is PEP 289,
> > universal and existential qualifiers.
> > I guess I'll have to wait.
> Why? Why not just stuff the code you wrote into an appropriately
> named function and use that?
> Anyway, here are more efficient implementations:
> def any(p, seq):
> """Returns true if any element in seq satisfies predicate p."""
> for elt in itertools.ifilter(p, seq):
> return True
> return False
Another alternative (also works for python2.2, but is likely to be slower):
def some(predicate, *seqs):
iterables = map(iter, seqs)
boo = predicate(*[iterable.next() for iterable in iterables])
if boo: return boo
except StopIteration: return False
More information about the Python-list